6

Why doesn't this query work?

DELETE FROM cancome WHERE user_id IN (
    SELECT user_id FROM cancome 
GROUP BY user_id
HAVING COUNT(user_id)>3 
  )
limit 3

I get this error message:

[Err] 1093 - You can't specify target table 'cancome' for update in FROM clause

0

1 Answer 1

29

The reason why this doesn't work is that MySQL doesn't allow you to reference the table that you are updating (cancome) within a subquery.

This can however be overcome by using a query instead of the table itself in the FROM, which has the effect of copying the requested table values instead of referencing the one that you are updating.

So effectively this, even if counter intuitive, will work :

DELETE FROM cancome WHERE user_id IN
 ( SELECT user_id FROM (SELECT * FROM cancome) AS cancomesub
 GROUP BY user_id HAVING COUNT(user_id)>3 )
 limit 3
Sign up to request clarification or add additional context in comments.

4 Comments

when i try this code that you were answerd i get this message "[Err] 1248 - Every derived table must have its own alias "
thank you its work
You're right, that is counter-intuitive, and you're also right, it worked like a charm. :-)
Is this guaranteed to run atomically?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.