Mysql:约束(补充)
1.1非空约束 NOT NULL
1.创建表时添加约束
2.创建表后,添加非空约束
alert table t_stu modify stu_name varchar(20) not null;
3.删除某字段的非空约束
alter table t_stu modify stu_name varchar(20);
1.2唯一约束 NUIQUE
1.创建表时,添加唯一约束
2.创建表后,添加唯一约束
alter table 表名 modify 要添加唯一约束的列名 unique;
3.删除唯一约束
alter table 表名 drop index 要删除唯一约束的列名
注意:mysql中,唯一约束限定的列的值可以有多个null
1.3.主键约束 PRIMARY KEY
1.创建表时,添加主键
2.创建表后,添加主键
alter table 表名 modify 要添加主键的列名 primary key;
3.删除主键
alter table 表名 drop primary key;
1.4自增长 auto_increment
概念:如果某一列是数值类型的,使用auto_increment可以来完成自增长
1.创建表时,添加主键约束,并完成主键自增长
2.添加自增长
alter table 表名 modify 列名 auto_increment;
3.删除自增长
alter table 表名 modify 列名;
1.5外键约束 foreign key
让表与表产生关系,从而保证数据的正确性
1.在创建表时,添加外键
create table 表名(
...
constraint 外键名称 foreign key (外键名称) references 主表名称(主表列名称)
);
2.创建表后,添加外键
alter table 表名 add constraint 外键名称 foreign key (外键字段名称) references 主表名称(主表列名称);
3.删除外键
alter table 表名 drop foreign key 外键名称;
4.级联操作
alter table 表名 add constraint 外键名称 foreign key (外键字段名称) references 主表名称(主表列名称) on update cascade on delete cascade;
级联更新:on update cascade
级联删除:on delete cascade
说明:
Mysql中没有check约束,实现自增长的关键字是auto_increment
SQLServer中存在check约束,实现自增长的关键字是identity(1,1) 表示从1开始+1
外键是用来保证数据的完整性的,即使没有外键 关联,也是可以实现多表查询的。