foreign keys

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

foreign keys

Post by Luke »

In a one-to-many relationship where I am working with the many side... for example users & articles... do I need to do anything special to the foreign key other than name it something like user_id in the articles table?
GM
Forum Contributor
Posts: 365
Joined: Wed Apr 26, 2006 4:19 am
Location: Italy

Post by GM »

No. You can call it what you like, but I personally find it easier to name it the same as in the other table.

This is why I avoid field names like "ID", because when you come to use this as a foreign key, you will probably already have a field called "ID" in the table.

I personally do this:

Code: Select all

CREATE TABLE user (
id_user INT(8) unsigned not null auto_increment,
de_user VARCHAR(8) not null,
...
...
PRIMARY KEY (id_user));

CREATE TABLE post (
id_post INT(8) unsigned not null auto_increment,
id_user INT(8) unsigned not null,
...
PRIMARY KEY (id_post));
Here the id_user is a foreign key to the post table, but I've kept the field name the same. Usually the fact that it begins with "id_" is enough to tell me a) that it is a foreign key and b) which table it is a key to.
Post Reply