Trying to explain the REFERENCES CONSTRAINT to someone else with a MySQL example, and I can’t make the pesky example work! It seems to work if I define it as a FOREIGN KEY, but I’ve textbooks that say I don’t have to do that (making it a column-level referential constraint rather than a table-level one).
The question is, after the UPDATE to dname in the dept table, why doesn’t the dname in the emp table change?
-- SQL CODE BEGINS
DROP TABLE IF EXISTS dept;
DROP TABLE IF EXISTS emp;
CREATE TABLE dept (
dname CHAR(10),
dnum numeric(3,0)
) ENGINE=InnoDB;
CREATE TABLE emp (
dname CHAR(10) REFERENCES dept(dname) ON UPDATE CASCADE,
ename CHAR(10)
) ENGINE=InnoDB;
INSERT INTO dept VALUES ("AAA", 111);
INSERT INTO dept VALUES ("BBB", 222);
INSERT INTO emp VALUES ("CCC", "Carol");
INSERT INTO emp VALUES ("AAA", "Alice");
SELECT * from dept;
SELECT * from emp;
UPDATE dept SET dname="XYZ" WHERE dnum=111;
SELECT * from dept;
SELECT * from emp;
-- SQL CODE ENDS
ARGH!
excerpted from MySQL 5.5 Reference Manual
<snip>
InnoDB does not recognize or support “inline REFERENCES specifications” (as defined in the SQL standard) where the references are defined as part of the column specification. InnoDB accepts REFERENCES clauses only when specified as part of a separate FOREIGN KEY specification. For other storage engines, MySQL Server parses and ignores foreign key specifications.
</snip>
http://dev.mysql.com/doc/refman/5.5/en/create-table.html
I think the authors of your two textbooks should have noted that their recommended approach, adding “REFERENCES” clause on the column definition, does NOT create or enforce foreign key constraints.
In order to create a foreign key constraint, you need a unique index on the target column(s). In your case, you nee an index on
dept(dname).With that in place, you can then create a foreign key constraint:
(Normally, a foreign key references the PRIMARY KEY of a table. But a UNIQUE KEY is sufficient. Actually, with InnoDB, all that is required is an index, it doesn’t have to be unique, but we don’t want to go there.)
To declare dname to be the PRIMARY KEY rather than a UNIQUE KEY:
When the
REFERENCESclause is added to the column definition, I believe that gets ignored by MySQL. (The syntax is accepted, but it doesn’t get recorded in the data dictionary. If you’re working with MyISAM it doesn’t matter, since MyISAM doesn’t enforce foreign key constraints.)To create foreign key constraints as part of the table definition, I put that on a separate line: