Skip to content
Advertisement

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');

Advertisement

Answer

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';
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement