MySQL: delete from IN

jmccartie picture jmccartie · Feb 13, 2011 · Viewed 10.3k times · Source

I know this is a simple syntax issue. Trying to delete all users from a subquery:

delete from users
where id IN (

select u.id
from users u 
where not exists (select * from stickies i where i.user_id = u.id) 
group by u.email 
having count(*) > 1

)

Getting this error:

error : You can't specify target table 'users' for update in FROM clause

The subquery works fine (returns list of user id's).

Answer

The Scrum Meister picture The Scrum Meister · Feb 13, 2011
DELETE u.*
FROM users u JOIN (
    SELECT u.id
    FROM users u LEFT JOIN stickies i ON i.user_id = u.id
    WHERE i.user_id IS NULL
    GROUP BY u.email 
    HAVING COUNT(*) > 1
  ) r ON r.id = r.id

Note: in the inner query, you are grouping by email, but selecting a user ID. this may return non deterministic results.