
在 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中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号