Mysql delete with subquery [duplicate]

2019-06-11 09:59发布

Possible Duplicate:
SQL Delete: can't specify target table for update in FROM clause

I'm trying to delete some rows, but is currently not in success.

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

You can't specify target table 'product_pictures' for update in FROM clause

I've never seen this error message before, nor has I been able to find some useful info about what I'm doing wrong.

Example of rows:

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

3条回答
2楼-- · 2019-06-11 10:35
DELETE a 
FROM product_pictures AS a
  JOIN product_pictures AS b
    ON b.picture = a.picture
WHERE b.id = ?

or:

DELETE a 
FROM product_pictures AS a
  JOIN 
    ( SELECT DISTINCT picture
      FROM product_pictures
      WHERE id = ?
    ) AS b
    ON b.picture = a.picture
查看更多
萌系小妹纸
3楼-- · 2019-06-11 10:35

Your query has a loop in it. Why don't you just do

DELETE FROM product_pictures
WHERE id = ?
查看更多
霸刀☆藐视天下
4楼-- · 2019-06-11 10:39
DELETE FROM product_pictures 
WHERE picture = (SELECT picture FROM (SELECT picture FROM product_pictures WHERE id = ?) x)

This cheat will fool mysql analyzer

查看更多
登录 后发表回答