在 MySQL 中,SERIAL 和 AUTO_INCREMENT 有什麼區別?


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

AUTO_INCREMENT 屬性受除 BIT 和 DECIMAL 之外的所有數字資料型別的支援。每個表只能有一個 AUTO_INCREMENT 欄位,並且一個表中的 AUTO_INCREMENT 欄位生成的序列不能用於任何其他表。 

此屬性要求該欄位上存在唯一的索引,以確保該序列沒有重複項。此序列預設從 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_INCREMENT。

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_INCREMENT 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)

更新於: 20-Jun-2020

3K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.