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 @   ascertain  阅读(577)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示