Adding a constraint to MySQL table
I have 2 tables one named Students and one named Grades and I'm trying to add a foreign key constraint to the Grades table so that if someone is deleted from the Students table all of their grades will be deleted as well. I have a column named TNumber to match the 2. Here's my code so far.
ALTER TABLE Grades
ADD CONSTRAINT fk_Grades
FOREIGN KEY (TNumber)
REFERENCES Students(TNumber) ON DELETE CASCADE;
The problem is that the code runs but it doesn't c开发者_如何学JAVAreate the foreign key. Could someone just look at it and see if I'm doing something wrong in my syntax because the code runs and doesn't throw any errors.
The most likely reason (and the one hinted at in the comments) given that the statement completes without error but seems to have no effect is that one or both of the tables use the MyISAM engine, which is usually the default. Both tables need to use an engine that supports foreign keys, such as InnoDB.
If your tables are MyISAM tables, you can convert them to InnoDB tables with the following:
ALTER TABLE Students Engine=InnoDB;
ALTER TABLE Grades Engine=InnoDB;
After that, try adding the foreign key again. A heads up: the columns in the foreign key constraint need to have the same type. If there are differences, you'll get the extremely unhelpful "ERROR 1005 (HY000): Can't create table filename (errno: 150)" error message.
Note that using the InnoDB engine has consequences (see also "Storage Engine Performance Benchmark for MyISAM and InnoDB" and whatever a web search may turn up) beyond allowing foreign key restraints, but most of them are beneficial.
精彩评论