I have a table site
that has a field categoryid_root
and a table category
which has the fields id
and parentid
I want to create a relationship between:
site.categoryid_root
and category.id
but with the condition that category.parentid
is null is this at all possible in MySQL?
Best Answer
It is not possible create a foreign key with a condition as you like. But you might use an intermediate table to simulate the condition. I call this table
category_root
. Thecategory_root
table will be updated only by triggers oncategory
table. So you can create the foreign key betweensite
table andcategory_root
tables. No users must be have grants to updatecategory_root
to prevent inconsistencies. See diagram to see how the tables are related to each other.The trigger for insert is defined so when an new category without parent_id is inserted into
category
a new row is insert also intocategory_root
table:The trigger for update is a little more complex:
Let try to insert some values:
If we try to add a site with a category_id with parent_id not null we got an error: