我该如何修复这个MySQL DELETE查询?

时间:2012-08-17 19:41:24

标签: mysql

我有三个表,productsshopssex。我希望product表中DELETE行的product_idproduct_id表中没有等效的sex

此外,products表中的这些行的shop_id必须等于shop_id表中的shops,其shops.shop值为{ 'www.shop.com'。

到目前为止我已经

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)

但似乎不能像我一样在子查询中引用products。 (我收到错误Unknown table 'products' in MULTI DELETE。)我如何解决错误?

1 个答案:

答案 0 :(得分:2)

您可以在JOIN声明中使用DELETE

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

这将DELETEshops表中具有shop = www.shop.com的相应行的产品,但仅当该产品也 <时em> not sex表中有相应的行。