知识点1:MySQL 主键具有非空性和唯一性。
设计表时,下面的指定主键的语句是否有问题?
create table sys_user (
id bigint not null auto_increment primary key comment '用户ID',
...
)
对于上面的代码,not null
和 auto_increment
是多余的。因为 mysql 的主键字段是非空的,并且是唯一的,即具有非空性和唯一性。
验证主键是否可以为空,以及是否可以不唯一:
create table test (
id int primary key
);
MariaDB [mybatis_test]> insert into test values (1);
Query OK, 1 row affected (0.006 sec)
MariaDB [mybatis_test]> select * from test;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.000 sec)
MariaDB [mybatis_test]> insert into test values (null); -- 验证非空性
ERROR 1048 (23000): Column 'id' cannot be null
MariaDB [mybatis_test]> insert into test values (1); -- 验证唯一性
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'