约束(Constraint)
约束在创建表的时候,可以给表的字段添加相应的约束,添加约束的目的是为了保证表中数据的合法性、有效性、完整性。
常见的约束:
-
非空约束(not null):约束的字段不能为NULL
-
唯一约束(unique):约束的字段不能重复
-
主键约束(primary key):约束的字段既不能为NULL,也不能重复,简称PK
-
外键约束(foreign key)简称FK
-
检查约束(check)
注意:Oracle数据库有check约束,但是MySQL没有,目前不支持该约束
非空约束 not null
drop table if exists t_user;
create table t_user(
id int,
username varchar(255) not null,
password varchar(255)
);
insert into t_user(id,password) values(1,'123');
ERROR 1364 (HY000): Field 'username' doesn't have a default value
insert into t_user(id,username,password) values(1,'lisi','123');
mysql> select * from t_user;
+------+----------+----------+
| id | username | password |
+------+----------+----------+
| 1 | lisi | 123 |
+------+----------+----------+
1 row in set (0.00 sec)
唯一性约束 unique
唯一约束的字段具有唯一性,不能重复,但可以为NULL。
案例:给某一列添加unique
drop table if exists t_user;
create table t_user(
id int,
username varchar(255) unique//列级约束
);
mysql> insert into t_user values(1,'zhangsan');
Query OK, 1 row affected (0.08 sec)
mysql> insert into t_user values(2,'zhangsan');
ERROR 1062 (23000): Duplicate entry 'zhangsan' for key 'username'//username重复了
insert into t_user(id) values(2);
insert into t_user(id) values(3);
insert into t_user(id) values(4);
mysql> select * from t_user;
+----