views:

64

answers:

2

I have a table which has one column as a foreign key joining to another table. It's a cricket question where I have a table called Fixtures and another called Inning.

Inning table has a FixtureId column relates to the Fixture table.

I would expect that If i do a insert on the inning table using a FixtureId that doesn't relate to a Fixture then it would error but this isn't the case...

Can anyone explain why this is?

+5  A: 

Make sure that you are using the InnoDB storage engine when creating the table. Other storage engines will simply ignore foreign key constraints. (Source)

Example:

CREATE TABLE a (
     id INT AUTO_INCREMENT PRIMARY KEY
) ENGINE=INNODB;

CREATE TABLE b (
     id INT AUTO_INCREMENT PRIMARY KEY,
     a_id INT,
     FOREIGN KEY (a_id) REFERENCES a(id)
) ENGINE=INNODB;

INSERT INTO b (id, a_id) VALUES(NULL, 1);

The above insert fails with:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails...

Daniel Vassallo
In addition to that, the inline `REFERENCES` keyword is ignored by InnoDB. You **must** use the `FOREIGN KEY` syntax instead: http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
R. Bemrose
brillient thanks
Steve
A: 

im not sure i understand can you elaborate and show your sql statements? if i understand correctly, ( which i may not ) your foreign key would just be blank if you did not have a value for that field, why would it error out?

David Morrow