MySQL中的外键基础 [英] Basics of Foreign Keys in 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屋!