代码改变世界

SQL使用指南(2)—— 约束的使用

2017-01-10 18:26  bongxin  阅读(187)  评论(0编辑  收藏  举报

主键约束

(1)创建表时添加主键约束

primary key<column_name>

(2) 修改表时添加主键约束

ALTER TABLE table_name
ADD CONSTRAINTS constraint_name PRIMARY KEY(column_name);

(3) 修改表时移除主键约束

ALTER TABLE table_name 
DROP CONSTRAINT constraint_name;

外键约束

(1)创建表时添加外键约束

CONSTRAINT constraint_name 
FOREIGN KEY(column_name) 
REFERENCE table_name(column_name)
ON DELETE CASCADE;

(2)修改表时创建外键约束

ADD CONSTRAINT constraint_name 
FOREIGN KEY(column_name) 
REFERENCE table_name(column_name) 
ON DELETE CASCADE;

(3) 修改表时移除外键约束

ALTER TABLE table_name 
DROP CONSTRAINT constraint_name;