jela
jela

Reputation: 1469

how do I fix this MySQL DELETE query?

I have three tables, products, shops, and sex. I wish to DELETE rows in the products table having a product_id such that there exists no equivalent product_id in the sex table.

Further, these rows in the products table must have a shop_id equal to the shop_id in the shops table for the row whose shops.shop value is 'www.shop.com'.

so far I have

DELETE FROM products USING shops WHERE
products.shop_id=shops.shop_id AND
shops.shop='www.shop.com' AND NOT EXISTS
(SELECT sex.product_id FROM sex WHERE
sex.product_id=products.product_id)

but it appears it is not acceptable to make reference to products in the subquery as I have done. (I get the error Unknown table 'products' in MULTI DELETE.) How do I fix my mistake?

Upvotes: 0

Views: 72

Answers (1)

Zane Bien
Zane Bien

Reputation: 23125

You can use JOINs in your DELETE statement:

DELETE    a 
FROM      products a
JOIN      shops b ON a.shop_id = b.shop_id AND b.shop = 'www.shop.com'
LEFT JOIN sex c ON a.product_id = c.product_id
WHERE     c.product_id IS NULL

This will DELETE only the products which have a corresponding row in the shops table with shop = www.shop.com, but only if that product also does not have a corresponding row in the sex table.

Upvotes: 2

Related Questions