MySQL: 外键 foreign key constraint

 

  1. 取消外键约束
    set @@foreign_key_check=0

     

  2. describe information_schema.key_column_usage;

     

     

     

     

  3. 查看表上的索引和foreign key
    select * from information_schema.key_column_usage where table_name='b'\G

     

     

  4. 查看表的哪个column被哪个表的column所引用
    select * from information_schema.key_column_usage where referenced_table_name='a'\G

     

     

     

  5. 新建两张测试表

     

     

     

  6.  增加外键约束

    alter table b
    add constraint fk_b_a foreign key (id_a) references a (id) on update cascade on delete cascade;

     

  7. 删除外键约束
    alter table b drop foreign key fk_b_a;

     

  8. 外键的约束关系
    父表: 被引用的表,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默认行为,立即检查外键约束

     

  9. 查询表的外键

     

    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';


     

     

  10.  

    父表被引用column必须是 primary key 或 unique key, 而且不是是subpart
  11. alter table tbl_name add [constraint [symbol]] foreign key [index_name] (columns,....) reference_opion

     

     

     

     

     

     

     

     


     

posted @ 2020-12-22 11:45  ascertain  阅读(603)  评论(0)    收藏  举报