MySQL FK 的正确命名约定是什么?

2022-01-20 00:00:00 naming-conventions foreign-keys mysql

由于它们必须是唯一的,我应该在 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.

相关文章