简体   繁体   中英

How to delete conditional parent child relation in SQL

I have a parent child relation A, B and C and would like to delete rows according following rules:

  1. If C exists, delete C
  2. then, if B has no Cs, delete B
  3. then, if A has no Bs, delete A

I wonder how a SQL (MySQL Version 7) query should look like to implement this rules. The rules must apply to one query or stored procedure.

在此处输入图片说明

My first idea was to use 'Common Table Expression' but found out that this is available in MySQL Version 8.

Could somebody point me in the right direction?

  1. For C there is no constraint violation.
  2. DELETE FROM B WHERE NOT EXISTS(SELECT * FROM C where idB = B.id)
  3. DELETE FROM A WHERE NOT EXISTS(SELECT * FROM B where idA = A.id)

By this way you are checking if a foreign key is going to be violated before executing the deletion. For large tables you should consider adding indices.

I generally avoid them as they can cause a performance nightmare when overused, but this sounds like pretty much the exact use case of a trigger, assuming you always want this to happen.

Triggers are executed in response to other changes in the database automatically, so it would be handled for you implicitly when you did other things (like deleting a row from B or C).

Here's an example from another post: phpMyAdmin create a trigger for deleting a parent row when no child rows exist .

You could have one trigger handling the BC parent relationship and one handling the AB one. They should chain fine I believe.

I think you're looking for something like this

SELECT Employees.ID, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Employees
LEFT JOIN Orders ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY Employees.ID
HAVING COUNT(Orders.OrderID) = 0;

Where Employees = A and Orders = B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM