MySQL中的外键基础 [英] Basics of Foreign Keys in MySQL?

查看:165
本文介绍了MySQL中的外键基础的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有对如何使用MySQL的外键构造有很好的解释?



我不完全从MySQL文档中得到它本身。直到现在,我一直在处理像加入和编程代码的外键。



问题的第二部分是否有任何改进可以通过使用MySQL内置的外键来实现?

解决方案

FOREIGN KEYS 确保您的数据是一致的。

如果你的关系是这样的:




$ $ b

  CREATE TABLE部门(ID INT NOT NULL)
CREATE TABLE雇员(id INT不空,dept_id INT NOT NULL,FOREIGN KEY(dept_id)REFERENCES部门))

,那么您不能删除部门如果它有一些员工



如果您提供 ON DELETE CASCADE FOREIGN KEY 定义,引用行将被自动删除和引用行。



作为一个约束, FOREIGN KEY 实际上会减慢t他有点疑问。

从引用表中删除或插入到引用表中时,需要执行额外检查。


Is there any good explanation of how to use MySQL's foreign key construct?

I don't quite get it from the MySQL docs themselves. Up until now I've been handling things like foreign keys with joins and programming code.

And the second part of the question, are there any improvements to be made by using MySQL's inbuilt foreign keys?

解决方案

FOREIGN KEYS just ensure your data are consistent.

They do not improve queries in sense of efficiency, they just make some wrong queries fail.

If you have a relationship like this:

CREATE TABLE department (id INT NOT NULL)
CREATE TABLE employee (id INT NOT NULL, dept_id INT NOT NULL, FOREIGN KEY (dept_id) REFERENCES department(id))

, then you cannot delete a department if it has some employee's.

If you supply ON DELETE CASCADE to the FOREIGN KEY definition, the referencing rows will be deleted automatically along with the referenced ones.

As a constraint, FOREIGN KEY actually slows down the queries a little.

Extra checking needs to be performed when deleting from a referenced table or inserting into a referencing one.

这篇关于MySQL中的外键基础的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆