MySQL表添加约束的相关语句

一、给表添加约束
1.创建表时添加
1)直接在数据类型后添加(这样无法设置索引名)
列名1 数据类型1 primary key,
列名2 数据类型2 unique [key],
列名3 数据类型3 not null,
列名4 数据类型4 default 默认值

2)定义完数据类型后再添加(可以设置索引名)
[constraint 索引名] primary key (列名),
[constraint 索引名] unique [key] (列名),
[constraint 索引名] foreign key (外键列名) references 其它表(主键名),
index/key 索引名 (列名)

2.创建表后再添加
alter table 表名 add [constraint 索引名] primary key (列名);
alter table 表名 add [constraint 索引名] unique key (列名);
alter table 表名 add [constraint 索引名] foreign key (外键列名) references 其它表(主键名) [on update cascade];
alter table 表名 add key 索引名 (列名);

二、删除约束
alter table 表名 drop index primary key;
alter table 表名 drop index 索引名;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容