What is a proper naming convention for MySQL FKs?

前端 未结 4 2082
醉酒成梦
醉酒成梦 2020-12-12 11:52

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

4条回答
  •  孤街浪徒
    2020-12-12 12:19

    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.

提交回复
热议问题