0

I am using the following query, which I saw from another stackoverflow question but I am getting error.

delete from mytable
 where myid not in (
    select max(myid)
      from mytable
group by myid2)

Error:

#1093 - Table 'mytable' is specified twice, both as a target for 'DELETE' and as a separate source for data

Edit 2:

I also tried this query:

delete from mytable
 where myid in (
    SELECT
    myid, COUNT(*)
FROM
    mytable
GROUP BY
    myid2
HAVING 
    COUNT(*) > 1)

And got this error:

#1241 - Operand should contain 1 column(s)

3
  • Your query doesn't make sense. You have max(myid) and group by myid. This will delete no rows. Commented May 26, 2019 at 12:13
  • I will try that. I changed myid in group by to myid2 (they are different id, and contain same duplicate rows). But I sitll get the same error Commented May 26, 2019 at 12:19
  • @GordonLinoff . Commented May 26, 2019 at 12:43

1 Answer 1

1

In MySQL, you need to use a JOIN for this purpose. I assume you mean something like this:

delete t
   from mytable t left join
        (select max(myid) as myid
         from mytable
         group by myid2
        ) tt
        on t.myid = tt.myid
   where tt.myid is null;

Where ? is whatever you really want to group by. Your version will not delete anything because the group by and max() use the same column.

Sign up to request clarification or add additional context in comments.

3 Comments

I will try that. I changed myid in group by to myid2 (they are different id, and contain same duplicate rows). But I sitll get the same error
I am getting this error Unexpected keyword. (near "join" at position 9)
@johndoe . . . That was a typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.