What is a proper naming convention for MySQL FKs?(MySQL FK 的正确命名约定是什么?)
问题描述
由于它们必须是唯一的,我应该在 MySQL 数据库中命名 FK 的什么?
Being that they must be unique, what should I name FK's in a MySQL DB?
推荐答案
在 MySQL 中,不需要给外键约束一个符号名.如果没有给出名称,InnoDB 会自动创建一个唯一的名称.
In MySQL, there is no need to give a symbolic name to foreign key constraints. If a name is not given, InnoDB creates a unique name automatically.
无论如何,这是我使用的约定:
In any case, this is the convention that I use:
fk_[referencing table name]_[referenced table name]_[referencing field name]
例子:
CREATE TABLE users(
user_id int,
name varchar(100)
);
CREATE TABLE messages(
message_id int,
user_id int
);
ALTER TABLE messages ADD CONSTRAINT fk_messages_users_user_id
FOREIGN KEY (user_id) REFERENCES users(user_id);
我尝试在引用表和被引用表中使用相同的字段名称,如上例中的 user_id 所示.当这不切实际时,我还将引用的字段名称附加到外键名称.
I try to stick with the same field names in referencing and referenced tables, as in user_id in the above example. When this is not practical, I also append the referenced field name to the foreign key name.
这种命名约定允许我通过查看表定义来猜测"符号名称,此外它还保证了名称的唯一性.
This naming convention allows me to "guess" the symbolic name just by looking at the table definitions, and in addition it also guarantees unique names.
这篇关于MySQL FK 的正确命名约定是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL FK 的正确命名约定是什么?
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
