简体   繁体   中英

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?

You can use JOIN s 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.

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