Mysql通过sql语句添加约束和查看约束

一:添加约束

1.添加唯一约束:alter table student add constraint uk_name unique(name);

2.添加外键约束:

alter table 表名

add constraint fk_字段名

foreign key (字段名) references 关联的表名(关联的字段名)

3.添加check约束:

alter table 表名

add constraint CK_字段名

check (条件表达式)

4.添加默认值约束:

alter table 表名

add constraint DF_字段名

default '默认值' for 字段名

5.删除约束:

alter table 表名

drop constraint 约束名

二:查询约束和触发器

1.查询约束:SELECT * FROM information_schema.`TABLE_CONSTRAINTS`;(可以通过where table_name='student'来约定只查询某个表的约束)

其实每次添加约束都是将添加的约束的信息存储到了information_schema这个schema的table_constraints表里;(mysql里``和bash的很像,也是执行``内的表达式而不是将里面作为字符串使用)

2.查看所有的触发器:select* from information_schema.triggers;

猜你喜欢

转载自www.cnblogs.com/silentdoer/p/8979730.html
今日推荐