什么是适用于MySQL FK的命名约定? [英] What is a proper naming convention for MySQL FKs?

查看:187
本文介绍了什么是适用于MySQL FK的命名约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MySQL中,有一个名为FK的应用程序,不需要给外键约束赋予符号名称。如果没有给出名字,InnoDB会自动创建一个唯一的名字。



无论如何,这是我使用的惯例:

  fk_ [引用表名] _ [引用表名] _ [引用字段名称] 

例子:

pre $ CREATE TABLE用户(
user_id int,
name varchar(100)
);

CREATE TABLE消息(
message_id int,
user_id int
);

ALTER TABLE消息ADD CONSTRAINT fk_messages_users_user_id
FOREIGN KEY(user_id)REFERENCES users(user_id);

我尝试在引用表和引用表中使用相同的字段名称,如<$ c $在上面的例子中,c> user_id 。当这不实际时,我也将引用的字段名称追加到外键名称。



这个命名约定允许我通过查看表定义来猜测符号名,另外它还保证了唯一的名字。 $ b

Being that they must be unique, what should I name FK's in a MySQL DB?

解决方案

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]

Example:

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);

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的命名约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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