简体   繁体   中英

How do I delete a row from one table, when no more rows exist in another

I would like to know the best way to check one table of data, and when no more rows exist matching the WHERE clause, delete a row from another table.

I have tried myself but it has become too cumbersome with 6 queries and nested if/else, and it doesn't work to top it off.

I have never used SQL join's before, so examples will help me to understand responses.

I have a table of devices, there is a master table with a device and a password.

There is a second table containing the multiple rows of the device in the above table, and a series of serial numbers.

When the second table no longer contains any of the serial numbers listed in the master table, I want the row containing the device and password from the master table.

If you mean like when you have a table customer and a table order, delete the customers if they have no orders? Then you can use subselect:

delete from customer where customerid not in (select customerid from order)

You coult make a DELETE statement like

DELETE FROM masterTable WHERE ID NOT IN (SELECT masterTableID FROM secondaryTable)

This would delete all the rows from the master-table which don't have any references in the second table. That also means it would not delete only one row, but all of the matching ones. The only necessary thing you need is that every row in the second table references to the master table.

DELETE table_devices
FROM table_devices
left JOIN serial ON table_devices.id= serial.device_id
WHERE serial.device_id is null

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