Being that they must be unique, what should I name FK's in a MySQL DB?
+5
A:
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.
Daniel Vassallo
2010-02-10 23:01:39
+1 personally, I would drop the `fk_` part, but that is down to taste.
Pekka
2010-02-10 23:04:25
@Pekka: Yes, in fact, I have mixed feelings about that too :)
Daniel Vassallo
2010-02-10 23:06:32
OMG Ponies
2010-02-10 23:14:45