首頁  >  文章  >  資料庫  >  在MySQL中,SERIAL和AUTO_INCRMENT有什麼不同?

在MySQL中,SERIAL和AUTO_INCRMENT有什麼不同?

WBOY
WBOY轉載
2023-08-24 15:09:031043瀏覽

在MySQL中,SERIAL和AUTO_INCRMENT有什麼不同?

在 MySQL 中,SERIAL 和 AUTO_INCRMENT 都用於將序列定義為欄位的預設值。但它們在技術上是不同的。

除 BIT 和 DECIMAL 之外的所有數位資料類型都支援 AUTO_INCRMENT 屬性。每個表只能有一個 AUTO_INCRMENT 字段,且一個表中 AUTO_INCRMENT 字段產生的序列不能在任何其他表中使用。

此屬性要求欄位上存在 UNIQUE 索引,以確保序列沒有重複項。預設情況下,序列從 1 開始,每次插入都會加 1。

範例

mysql> Create Table Student(Student_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));
Query OK, 0 rows affected (0.18 sec)

上面的查詢宣告 Student_id AUTO_INCRMENT。

mysql> Insert Into Student(Name) values('RAM'),('SHYAM');
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from Student;
+------------+-------+
| Student_id | Name  |
+------------+-------+
|          1 | RAM   |
|          2 | SHYAM |
+------------+-------+
2 rows in set (0.00 sec)

mysql> Show Create Table Student\G
*************************** 1. row ***************************
      Table: Student
Create Table: CREATE TABLE `student` (
   `Student_id` int(11) NOT NULL AUTO_INCREMENT,
   `Name` varchar(20) DEFAULT NULL,
   PRIMARY KEY (`Student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

另一方面,SERIAL DEFAULT VALUE 是 NOT NULL AUTO_INCRMENT UNIQUE KEY 的簡寫。 TINYINT、SMALLINT、MEDIUMINT、INT 和 BIGINT 等整數數值類型支援 SERIAL DEFAULT VALUE 關鍵字。

範例

mysql> Create Table Student_serial(Student_id SERIAL, Name VArchar(20));
Query OK, 0 rows affected (0.17 sec)

mysql> Insert into Student_serial(Name) values('RAM'),('SHYAM');
Query OK, 2 rows affected (0.12 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from Student_serial;
+------------+-------+
| Student_id | Name |
+------------+-------+
|          1 | RAM   |
|          2 | SHYAM |
+------------+-------+
2 rows in set (0.00 sec)

mysql> Show Create Table Student_serial\G
*************************** 1. row ***************************
      Table: Student_serial
Create Table: CREATE TABLE `student_serial` (
   `Student_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
   `Name` varchar(20) DEFAULT NULL,
   UNIQUE KEY `Student_id` (`Student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
#

以上是在MySQL中,SERIAL和AUTO_INCRMENT有什麼不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除