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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律