views:

40

answers:

2

I wish to have a foreign key in a table but I have no idea how to do it. I wish have a UserID Column in the "wall" table so that I can link back and get the userid's details etc. How would i go about doing this?

Wall Table: alt text

Users Table: alt text

+2  A: 

1) In order to have a foreign key column called userid in the WALL table, you need to create the column - skip to #2 if the column already exists:

ALTER TABLE WALL
  ADD COLUMN userid INT(25) NOT NULL

If you want to allow WALL records to exist without the userid being specified:

ALTER TABLE WALL
  ADD COLUMN userid INT(25) NULL

2) Now you add the foreign key constraint:

ALTER TABLE WALL
 ADD FOREIGN KEY (userid) REFERENCES USERS(userid)
OMG Ponies
Thanks so far, however I get "#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'REFERENCES users(UserID)' at line 2"When i run ALTER TABLE WALL ADD FOREIGN KEY userid REFERENCES USERS(userid)
ritch
@ritch: Fixed - I forgot to put brackets around the FK column name.
OMG Ponies
Put parentheses around "userId" after ADD FOREIGN KEY. The parentheses are not optional, nor are they redundant. You can have a foreign key that consists of multiple columns, and they'd all go inside the parentheses: (colA, colB).
siride
@OMG Ponies: you are too fast!
siride
@OMG Ponies: Thanks for this
ritch
+1  A: 

Add a UserID column to the Wall table and then create a foreign key on it. In SQL, it'd look like this:

CREATE TABLE Wall (
    ...
    UserID INT,
    ...
    FOREIGN KEY (UserID) REFERENCES User (UserID) ON UPDATE CASCADE ON DELETE RESTRICT,
    ...
) ENGINE=InnoDB;

Note that you may not want to have ON DELETE RESTRICT. That's the most restrictive option. Read up about it on the MySQL website: http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html

siride
OMG Ponies
I wanted to make it clear in the table structure. I considered using the ALTER TABLE syntax, but I thought that'd make it less obvious. Six in one, half dozen the other and all that.
siride
+1: For demonstrating how to implement the FK in the CREATE TABLE statement
OMG Ponies
thanks for the help guys
ritch