Basics of Foreign Keys in MySQL?(MySQL中外键的基础知识?)
问题描述
关于如何使用 MySQL 的外键构造有什么好的解释吗?
Is there any good explanation of how to use MySQL's foreign key construct?
我并不能完全从 MySQL 文档本身中得到它.到目前为止,我一直在处理诸如外键连接和编程代码之类的事情.
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.
问题的第二部分,使用 MySQL 的内置外键是否有任何改进?
And the second part of the question, are there any improvements to be made by using MySQL's inbuilt foreign keys?
推荐答案
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.
如果你有这样的关系:
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))
,那么如果一个department
有一些employee
,你就不能删除它.
, then you cannot delete a department
if it has some employee
's.
如果您将 ON DELETE CASCADE
提供给 FOREIGN KEY
定义,则引用行将与被引用行一起自动删除.
If you supply ON DELETE CASCADE
to the FOREIGN KEY
definition, the referencing rows will be deleted automatically along with the referenced ones.
作为一个约束,FOREIGN KEY
实际上会稍微减慢查询速度.
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中外键的基础知识?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL中外键的基础知识?
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01