MySQL: 外键 foreign key constraint
- 取消外键约束
set @@foreign_key_check=0
-
describe information_schema.key_column_usage;
- 查看表上的索引和foreign key
select * from information_schema.key_column_usage where table_name='b'\G
- 查看表的哪个column被哪个表的column所引用
select * from information_schema.key_column_usage where referenced_table_name='a'\G
- 新建两张测试表
-
增加外键约束
alter table b add constraint fk_b_a foreign key (id_a) references a (id) on update cascade on delete cascade;
- 删除外键约束
alter table b drop foreign key fk_b_a;
- 外键的约束关系
父表: 被引用的表,column必须为primary key 子表: 引用主表,外键的某一column引用父表的primary key cascade: 在父表update/delete,同步update/delete子表的记录 set null: 在父表update/delete,将子表的外键与主表主键匹配的记录设为null(子表外键不能为not null) no action: 子表的外键有记录与主表主键关联,则不允许对主表的相关主键进行update/delete restrict: 同 no action,MySQL默认行为,立即检查外键约束
-
查询表的外键
select constraint_schema,constraint_schema, table_name,column_name, referenced_table_name,referenced_table_name, from information_schema.key_column_usage where constraint_schema='cruft' and table_name='emp' and referenced_table_name='dept';
-
- alter table tbl_name add [constraint [symbol]] foreign key [index_name] (columns,....) reference_opion