Question

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).

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top