使用子查询删除Mysql

时间:2011-12-15 22:31:28

标签: mysql subquery

  

可能重复:
  SQL Delete: can't specify target table for update in FROM clause

我正在尝试删除某些行,但目前尚未成功。

DELETE FROM product_pictures 
WHERE picture = (SELECT picture FROM product_pictures WHERE id = ?)

您无法在FROM子句

中为更新指定目标表'product_pictures'

我之前从未见过这条错误信息,也没有找到一些关于我做错的有用信息。

行示例:

ID    Picture
19    picture-grey.jpg
20    picture-grey.jpg
21    picture-grey.jpg

3 个答案:

答案 0 :(得分:10)

DELETE FROM product_pictures 
WHERE picture = (SELECT picture FROM (SELECT picture FROM product_pictures WHERE id = ?) x)

这个作弊会欺骗mysql分析器

答案 1 :(得分:3)

DELETE a 
FROM product_pictures AS a
  JOIN product_pictures AS b
    ON b.picture = a.picture
WHERE b.id = ?

或:

DELETE a 
FROM product_pictures AS a
  JOIN 
    ( SELECT DISTINCT picture
      FROM product_pictures
      WHERE id = ?
    ) AS b
    ON b.picture = a.picture

答案 2 :(得分:1)

您的查询中有一个循环。你为什么不这样做

DELETE FROM product_pictures
WHERE id = ?