Question

I have a query. I would like to delete all selected rows in these 3 different tables Since I have a lot of INNER joins, I couldn't figure it out. My goal is to delete everything for these seller_ids.

SELECT *
FROM orders a
 INNER JOIN order_items b ON a.order_id = b.order_id
 INNER JOIN order_item_histories c ON c.order_item_id = b.order_item_id
WHERE a.seller_id IN (1, 3)

Version Postgres 10.3

I tried this but I couldn't succeed.

DELETE
FROM  
   USING orders
   USING order_items,
   USING order_item_histories
WHERE orders.order_id = order_items.order_id AND order_items.order_item_id = order_item_histories.order_item_id
AND  orders.seller_id IN (1, 3)
Was it helpful?

Solution

A DELETE statement can only delete from one table (unless there are triggers or foreign keys with ON DELETE CASCADE options defined).

To overcome the problem you can either use 3 DELETE statements:

DELETE FROM order_item_histories
WHERE order_item_id IN
      ( SELECT b.order_item_id 
        FROM order_items AS b
             JOIN orders AS a
               ON a.order_id = b.order_id
        WHERE a.seller_id IN (1, 3)
      )
RETURNING order_item_id, order_item_history_id ;

DELETE FROM order_items 
WHERE order_id IN 
      ( SELECT order_id
        FROM orders
        WHERE seller_id IN (1, 3)
      )
RETURNING order_id, order_item_id ;

DELETE FROM orders
WHERE seller_id IN (1, 3)
RETURNING order_id ;

or by chaining (data modifying) CTEs:

WITH 
  a AS 
  ( DELETE FROM orders
    WHERE seller_id IN (1, 3)
    RETURNING order_id
  ),
  b AS
  ( DELETE FROM order_items 
    WHERE order_id IN (SELECT order_id FROM a)
    RETURNING order_id, order_item_id 
  ),
  c AS
  ( DELETE FROM order_item_histories
    WHERE order_item_id IN (SELECT order_item_id FROM b)
    RETURNING order_item_id, order_item_history_id
  )
SELECT
    a.order_id,
    b.order_item_id, 
    c.order_item_history_id
FROM a
  LEFT JOIN b ON a.order_id = b.order_id
  LEFT JOIN c ON c.order_item_id = b.order_item_id ;

OTHER TIPS

If you have more than one join you could use comma separated USING statements:

DELETE 
FROM 
      AAA AS a 
USING 
      BBB AS b,
      CCC AS c
WHERE 
      a.id = b.id 
  AND a.id = c.id
  AND a.uid = 12345 
  AND c.gid = 's434sd4'

Reference

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top