Correct: no, prevent: yes!
This should not happen if you set your constraints properly: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
Pregunta
I'm using a MySQL database. I have two tables, Table 1 and Table 2. There is a composite primary key in Table 1. There is a composite foreign key in Table 2 that references the Composite PK in Table 1.
The problem I have is illustrated below:
Table 1
|------------PK-----------|
menuid | categoryid | categoryname
1 |1 |myCategoryName1
1 |2 |myCategoryName2
2 |1 |myCategoryName3
2 |2 |myCategoryName4
2 |3 |myCategoryName5
I can create an entry in Table 2 that is referencing a false entry in Table 1:
Table 2
|------------FK-----------| |----PK----|
menuid | categoryid | postid |post name
1 |3 |1 |myPostName
Now, it's not a big problem since I can insert valid values into the database. However, this seems like a relational error in the database and I would like to have a clean, correctly-functioning DB. Is there a way to correct this minor problem?
UPDATE: I was using phpMyAdmin to implement my database and apparently there is no way of implementing composite foreign keys in phpMyAdmin. I was able to look at my incorrectly-implemented foreign key via
SHOW CREATE TABLE Table2
where Table2
is the name of my second table with the composite foreign key.
Then I correctly added composite foreign key manually via
ALTER TABLE Table2 ADD CONSTRAINT my_fk_constraint
FOREIGN KEY (menuid, categoryid)
REFERENCES Table1(menuid, categoryid)
where my_fk_constraint
is the name of the constraint being added.
Note: Manually adding foreign key constraints this way does not allow you to use a drop-down menu when inserting new entries (nor referring to the corrresponding table by clicking on the FK columns), as you would normally be able to in phpMyAdmin.
Thanks pst
and thedayofcondor
, you are both correct because I'm a small-dicked freak using phpMyAdmin.
Solución
Correct: no, prevent: yes!
This should not happen if you set your constraints properly: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html