What is a proper naming convention for MySQL FKs?

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

    If you don't find yourself referencing fk's that often after they are created, one option is to keep it simple and let MySQL do the naming for you (as Daniel Vassallo mentions in the beginning of his answer).

    While you won't be able to uniquely "guess" the constraint names with this method - you can easily find the foreign key constraint name by running a query:

    use information_schema;
    select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from KEY_COLUMN_USAGE where REFERENCED_TABLE_SCHEMA = 'your_db_schema_name' ORDER BY TABLE_NAME;
    

    For example you might receive the following from the query:

    +------------+-------------+-----------------+-----------------------+------------------------+
    | TABLE_NAME | COLUMN_NAME | CONSTRAINT_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |
    +------------+-------------+-----------------+-----------------------+------------------------+
    | note       | taskid      | note_ibfk_2     | task                  | id                     |
    | note       | userid      | note_ibfk_1     | user                  | id                     |
    | task       | userid      | task_ibfk_1     | user                  | id                     |
    +------------+-------------+-----------------+-----------------------+------------------------+
    

    If this extra step isn't too much for you, then you should be able to easily find the fk you are looking for.

提交回复
热议问题