MySQL 非空约束位置不同对自增列造成的影响

MySQL版本
select version();
+------------+
| version() |
+------------+
| 5.7.21-log |
+------------+
1 row in set (0.00 sec)


非空约束为null 并在自增列属性前

  • 即使自增列的非空约束定义可以为 null,但实际自增列为not null

create table test_auto_incre(id int null auto_increment,id2 int default null ,key idx_id(id));

show create table test_auto_incre;

CREATE TABLE test_auto_incre (
id int(11) NOT NULL AUTO_INCREMENT,
id2 int(11) DEFAULT NULL,
KEY idx_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

insert into test_auto_incre(id2) values(12),(2312);
select * from test_auto_incre;
+----+------+
| id | id2 |
+----+------+
| 1 | 12 |
| 2 | 2312 |
+----+------+
2 rows in set (0.00 sec)


非空约束为null 并在自增列属性后

  • 自增列定义可以为null,实际自增列也可以为null;自增列失去作用!

create table test_auto_incre2(id int auto_increment null,id2 int null,key idx_id(id));
Query OK, 0 rows affected (0.02 sec)

非空约束在自增列属性后,不是MySQL的标准建表语句,但建该表没有报错和警告
show create table test_auto_incre2;

CREATE TABLE test_auto_incre2 (
id int(11) AUTO_INCREMENT,
id2 int(11) DEFAULT NULL,
KEY idx_id (id)
) ENGINE=InnoDB;

插入数据

insert into test_auto_incre2(id2) values(12),(2312);
select * from test_auto_incre2;
+------+------+
| id | id2 |
+------+------+
| NULL | 12 |
| NULL | 2312 |
+------+------+
2 rows in set (0.00 sec)


非空约束为not null 并在自增列属性后

create table test_auto_incre2(id int auto_increment not null,id2 int null,key idx_id(id));

show create table test_auto_incre2;

CREATE TABLE test_auto_incre2 (
id int(11) NOT NULL AUTO_INCREMENT,
id2 int(11) DEFAULT NULL,
KEY idx_id (id)
) ENGINE=InnoDB A

插入数据

insert into test_auto_incre2(id2) values(12),(2312);
select * from test_auto_incre2;
+----+------+
| id | id2 |
+----+------+
| 1 | 12 |
| 2 | 2312 |
+----+------+

MySQL标准建表语法
297e380e8d580397b0fc6cbf3b967fe7.png

posted on   jiaxin666  阅读(353)  评论(0编辑  收藏  举报

编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示