Okay, I desperately lack time to write full articles posts lately, so I’m going to make this quick! :P
Background: Suppose you have a table named Songs
and a table named Genres
. Genres
only contains Genre IDs and Genre Names. Songs
contains all sorts of data, but at some point there is one field (let’s call it Song_Genre_ID
) that points to the Genre ID. Get the picture? I’m sorry, I don’t have the time for an actual picture of this. That “pointer” is called a Foreign Key. The Genre_ID
, being the Primary key.
Data Integrity Enforcement means that MySQL is going to prevent you from putting any crappy value into the Foreign Key (FK) that would not exist in the refered Primary Key (PK). It will also prevent you from deleting a Genre if there are songs pointing to it. The bottom line is: if you’re serious about your DB, you can’t do without!
Now how would you enforce the integrity? Basically with something like this (but you may want to check the MySQL manual for details, right? :P):
ALTER TABLE Songs
ADD CONSTRAINT FK_any_name
FOREIGN KEY (Song_Genre_ID)
REFERENCES Genres (Genre_ID)
ON DELETE RESTRICT
ON UPDATE RESTRICT;
Now, here’s my point: from my experience I have found that a hell lot of things can go wrong when you try to add that constraint, and it can be a nightmare to find out what’s going wrong! As a matter of fact, you’ll find out MySQL’s error messages aren’t very helpful >:XX…
So here’s a checklist to follow in order to find out what’s been going wrong:
Okay I hope I didn’t forget anything. Of course, if you find another reason for the constraint creation to fail, I’d love to hear about it! ;)
Good luck! :»