I have a few tables in MySQL like so:
A ---- A_has_B ---- B
(many to many) |
|
C ---- C_has_B-------
(many to many)
I need to delete rows from B given that:
- The row to be deleted are referenced in C_has_B by C.C_ID
- The row to be deleted are not referenced by other C.C_IDs in C_has_B
- The row to be delete is also not referenced in A_has_B
I am able to get all the rows to be deleted referenced by C.ID using:
DELETE * FROM C
JOIN C_has_B
ON(C.C_ID = C_has_B.C_ID)
JOIN B
on(C_has_B.B_ID = B.B_ID)
where C.C_ID = 1;
I am not too sure how I can implement the last 2 conditions. Is it even possible to do this with just 1 query?
You want to delete rows from B that are referenced only once in C_has_B and not referenced by A_has_B.
With subqueries:
Without subqueries: