简体   繁体   中英

SQL Delete all rows in a table based on another table and another column value

table1:

|   ID        |  POST STATUS   |
|   12807     |  wc-refunded   | 
|   13075     |  wc-refunded   |

table2:

|   ORDER ID  |  -------   |
|   12807     |  -------   | 
|   13075     |  -------   |

Let me explain better, i want to delete all ORDER ID in table 2, based on all ID of table 1 if post_status = wc-refunded

MYSQL VERSION: 5.7

EDIT : fixed with first solution from the @Tim Biegeleisen ( THANKS! )

    DELETE
FROM wp_woocommerce_downloadable_product_permissions
WHERE EXISTS (SELECT 1 FROM wp_posts
              WHERE wp_posts.ID = wp_woocommerce_downloadable_product_permissions.order_id AND wp_posts.post_status = 'wc-refunded');

You could use exists logic:

DELETE
FROM table2 t2
WHERE EXISTS (SELECT 1 FROM table1 t1
              WHERE t1.ID = t2.ORDERID AND t1.poststatus = 'wc-refunded');

We can also try using delete join logic:

DELETE t2
FROM table2 t2
INNER JOIN table1 t1
    ON t1.ID = t2.ORDERID
WHERE t1.poststatus = 'wc-refunded';

Try this one:

DELETE FROM table2 
WHERE OrderID IN (
                    SELECT DISTINCT ID 
                    FROM table1
                    WHERE PostStatus = 'wc-refunded'
                 )

It is a bit resource intensive, but should work...

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