How to delete a child row (on delete cascade ?) when setting a null value on a parent?
Here’s the db design.
table A [id, b_id_1, b_id_2]
table B [id, other fields…]
b_id_1 and b_id_2 can be NULL
if any of them is null, it means NO B records for corresponding FK (there are 2 of them)
so (b_id_1,b_id_2) can be (null,null), (100, null), (null, 100_or_any_other_number) etc
How in one SQL query both set b_id_1 (or b_id_2) to null and delete all rows from B that have this id?
What FK design should be applied to the 2 tables?
THE QUERY SHOULD BE EXECUTED FROM THE PERSPECTIVE OF A TABLE!
Yes, if we use “On delete set null” and delete a record from B table it will work.
But the query MUST touch only A table !!
And you see, there’s not such a statement in mysql SQL syntax as “delete field value from a row”.
We can only set it to NULL.
That’s what I need.
Any ideas?
ON DELETE SET NULLhttp://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
UPDATE: If you want to do it from the perspective of A table (why on earth would you want that???), then you can’t get around a trigger, e. g.
Anyway, that won’t set to
NULLany values inAthat have the same value, because you cannot make a trigger in MySQL, that changes the same table that triggered the trigger.And generally, if you want weird stuff like this, I can assert with high probability that your database design is flawed. If you put more details, I could perhaps suggest a better one.