Mysql的四种约束

一、Mysql支持以下约束:

※  主键约束 :primary key

※  唯一性约束:unique key

※  外键约束:foreign key

※  非空约束:not null

※  默认值约束:default

二、主键约束:

一个表只能有一个主键,当建表时忘记设置主键约束时.设置为主键的列查询速度会非常快,所以一般会用聚集索引,这个我们后面会讲到。

添加主键约束:设置myself表的age为主键

alter table myself add primary key(age);

语法:alter  table 表名 add primary key;(列名)※  可以有多个列名

修改主键约束:将id设置为主键

alter table myself modify id int primary key;

语法:alter table 表名 modify 列名称  列类型 primary key;

删除主键约束:

alter table myself drop primary key;
语法:alter table 表名 drop primary key;

三、外键约束:

何为外键,当建表时需要用到另外一个表的主键作为本表的的主键时,需要设置外键。设置外间后,若想在删除本表数据时会级联删除或者默认删除其他方式。

添加外键约束:设置本表的cno为外键

alter table myself add foreign key cno references course(cno); 

语法:alter table 表名称 add foreign key (列名称)  references  关联表名称(列名称);

外键删除:

alter table myself drop foreign key myself_ibfk_1;

语法:alter table 表名称 drop foreign key 外键名称;   ※外键名和外键名称不一样

查询外键名:查询myself外键名

show create table myself


语法:show create table 表名

删除表时有两种模式:

※ on delete cascade  级联删除

※ on delete set null  表的关联列的值设置为null

四、非空约束:

当插入新数据时对应的列为不能空。非空约束是相对于默认值约束而说的。

添加非空约束:

alter table myself modify id int not null;

语法:alter table 表名 modify 列名 列类型 not null; 

修改非空约束:修改非空就是改为空

alter table myself modify id int null;

语法:alter table 表名 modify 列名 列类型 null

删除非空约束:删除非空约束就是设置为默认值

alter table modify id int default 'abe'
语法:alter table modify 列名 列类型 默认值;

五、默认值约束:default:

当插入时没有插入值时,会自动插入默认值。默认值约束相对于非空约束而说。

添加默认值约束:

alter table myself add id int not null default 'abc';

语法:alter table 表名 add 列名 列类型 not null default '默认值';

六、唯一性约束:

本列的内容只能唯一不能重复。

添加唯一约束:

alter table myself add unique(id);
 语法:alter table 列名 add unique(列名称)  ※可以有多个列名称,用逗号隔开。

修改唯一约束:

alter table myself modify id int unique;

语法:alter table 表名 modify 列名称 列类型 unique;

删除唯一约束:删除age列的唯一约束

alter table myself drop index age;

语法:alter table 表名称 drop index 列名称;

tip:mysql不支持check约束,要想达到check约束的效果,应将限制列设置为enum 枚举型。



猜你喜欢

转载自blog.csdn.net/weixin_41678001/article/details/80472679