约束

亡梦爱人 提交于 2020-02-12 00:40:09

主键约束

能够唯一确定一张表中的一条记录,也就是我们通过给某一字段添加约束,就可以使得该字段不重复且不为空
mysql> use test
Database changed
mysql> create table user(
-> id int primary key,
-> name varchar(20)
-> );
Query OK, 0 rows affected (0.14 sec)

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| pet |
| user |
+----------------+
2 rows in set (0.00 sec)

mysql> describe user;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.05 sec)

mysql> insert into user values('1','张三');
Query OK, 1 row affected (0.14 sec)

mysql> insert into user values('1','张三');
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
mysql> insert into user values('2','张三');
Query OK, 1 row affected (0.01 sec)

mysql> select * from user;
+----+------+
| id | name |
+----+------+
| 1 | 张三 |
| 2 | 张三 |
+----+------+
2 rows in set (0.00 sec)

mysql> insert into user values(NULL,'张三');
ERROR 1048 (23000): Column 'id' cannot be null

自增约束

外键约束

唯一约束

非空约束

默认约束

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!