在 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)
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP