What is a proper naming convention for MySQL FKs?

前端 未结 4 2061
醉酒成梦
醉酒成梦 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:12

    my choice is different. in my opinion, a table should have an id field, not a user_id one, because table is just called user, so:

    CREATE TABLE users(
       id    int,
       name       varchar(100)
    );
    
    CREATE TABLE messages(
       id int,
       user_id    int
    );
    

    user_id in messages table is a fk field so it has to make clear which id is (user_id).

    a fully-self-explaining naming convention, in my opinion, could be:

    fk_[referencing table name]_[referencing field name]_[referenced table name]_[referenced field name]
    
    i.e.: `fk_messages_user_id_users_id`
    

    note:

    • you can, in some case, omit the second element ([referencing field name])
    • this fk could is unique, because if a messages_user table exists, the referencing field name should be user_id (and not just id) and the fk name should be:

      fk_messages_user_user_id_users_id

    in other words, a foreign key naming convention make you sure about unique names if you also use a "referencing/referenced field" naming convention (and you can choose your own, of course).

提交回复
热议问题