知识点1:MySQL 主键具有非空性唯一性

设计表时,下面的指定主键的语句是否有问题?

  1. create table sys_user (
  2. id bigint not null auto_increment primary key comment '用户ID',
  3. ...
  4. )

对于上面的代码,not nullauto_increment 是多余的。因为 mysql 的主键字段是非空的,并且是唯一的,即具有非空性唯一性

验证主键是否可以为空,以及是否可以不唯一:

  1. create table test (
  2. id int primary key
  3. );
  1. MariaDB [mybatis_test]> insert into test values (1);
  2. Query OK, 1 row affected (0.006 sec)
  3. MariaDB [mybatis_test]> select * from test;
  4. +----+
  5. | id |
  6. +----+
  7. | 1 |
  8. +----+
  9. 1 row in set (0.000 sec)
  10. MariaDB [mybatis_test]> insert into test values (null); -- 验证非空性
  11. ERROR 1048 (23000): Column 'id' cannot be null
  12. MariaDB [mybatis_test]> insert into test values (1); -- 验证唯一性
  13. ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'