Wednesday, May 2, 2007

SQL: Adding foreign key relationships

Tip on adding foreign key relationships in SQL:

You can establish a foreign key relation in your create table or with an alter table statment, like this:

ALTER TABLE [table1_name]
ADD CONSTRAINT [constraint_name]
FOREIGN KEY ([field(s) from table1])
REFERENCES [table2_name] ([field(s) from table2])
ON [DELETE CASCADE, or UPDATE, or other command];

(BTW, in the example above, for a cascade, generally table1 would be the child table, and table2 would be the parent table)

If you get an error like this:
Error Code : 1005
Can't create table '.\test\#sql-ac_195.frm' (errno: 150)

it may be the case that your referenced field is not guaranteed unique, which it must be. If you don't have a single unique field in that table, you can use multiple fields to specify the unique key.

1 comment:

Skandalouz said...

Also the fields must be the same as signed or unsigned. This solved my problem.