简体   繁体   中英

Re-writing my query to delete from a select statement

Here's my query which in theory would be what I want but I know that MySQL won't let you use the same table in the sub-select as in the delete:

DELETE FROM manifestPallet WHERE palletID IN 
( SELECT  manifestPallet.palletID 
            FROM manifestPallet
            LEFT JOIN manifestBox
            ON manifestPallet.palletID = manifestBox.palletID
            WHERE manifestBox.palletID IS NULL)

I know I can do the select first, then loop through the results in my php script and do delete queries but I think there is probably a more elegant solution using pure MySQL.

Extra info: What the query does is delete pallets from a manifest that are empty. A user creates pallets then places boxes on them, if they create a pallet but don't put any boxes on it then the pallet needs to be removed when the manifest is closed.

DELETE manifestPallet
FROM   manifestPallet LEFT JOIN manifestBox USING (palletID)
WHERE  manifestBox.palletID IS NULL

You simply need to specify on which tables to apply the DELETE.

Delete only the manifestPallet rows:

DELETE `manifestPallet` FROM `manifestPallet` LEFT JOIN `manifestBox` ....

Delete the manifestPallet and manifestBox rows:

DELETE `manifestPallet`, `manifestBox` FROM `manifestPallet` LEFT JOIN `manifestBox` ....

Delete only the manifestBox rows:

DELETE `manifestBox` FROM `manifestPallet` LEFT JOIN `manifestBox` ....
DELETE FROM manifestPallet mp
WHERE NOT EXISTS (
    SELECT *
    FROM manifestBox mbx
    WHERE mp.palletID = mbx.palletID
    );

Note: there is a semantic difference with the original query, since the IN( subselect) term removes NULLs (and duplicates). This will probaly not cause differneces in the actual results, since the palletID is probably a NOT NULLable (primary) key.

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