I keep getting this error when attempting to create a table with SQL.
I have these two tables:
I’m using PHPMyAdmin and it won’t allow me to use M_id as a foreign key which references Employee Table primary key E_id.
Anyone able to see what’s wrong with my code?
Thanks!
3
Answers
Foreign key definitions have to exactly match the primary key columns to which they refer. In this case, you defined
Department.M_id
to a be a nullable integer column, whileEMPLOYEE.E_id
is integer not nullable. Try makingM_id
not nullable:Your code has multiple errors:
varchar()
length is too long.SET DEFAULT
doesn’t really work.You want something like this:
I also changed a few other things:
Here is a db<>fiddle showing that this works.
I will not question your design, though it looks problematic.
However – You cannot reference a table which doesn’t exist yet (
REFERENCES Department(D_id)
). You should either remove the FOREIGN KEY constraints from the CREATE statements and add them afterwards in ALTER TABLE statements.Example:
Demo
Or temporarily disable foreign key checks:
Demo
You can also not use
ON DELETE SET DEFAULT
. InnoDB doesn’t support it. You need to change it toON DELETE SET NULL
. If you want that behavior, you will need to implement it either in your application code or in a trigger.I would also use
TEXT
as data type instead ofVARCHAR(30000)
.