58

This is probably an easy one... how can I achieve what i want with this query:

delete from posts where id not in
(SELECT id FROM posts order by timestamp desc limit 0, 15)

so, to put it in a nutshell, I want to delete every post that isn't on the latest 15.

When I try that query, I get that

MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery

EDIT

mySQL Server version: 5.5.8
mySQL Client version: mysqlnd 5.0.7-dev - 091210 - $Revision: 304625 $

Error: #1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

1
  • What's the MySQL version? What is the EXACT error MySQL gives? Commented Aug 19, 2011 at 16:15

3 Answers 3

170

Try this:

DELETE 
FROM posts 
WHERE id not in (
      SELECT * FROM (
            SELECT id 
            FROM posts 
            ORDER BY timestamp desc limit 0, 15
      ) 
      as t);
Sign up to request clarification or add additional context in comments.

11 Comments

Thank you. It's kind of ridiculous that this works, but I'm glad it does.
I'm really curious about the reason why MySQL cannot support the original way described by OP...it's a weird limitation.
I don't understand why this works as there's not explanation whatsoever.
it is funny when the sub query does not work but the sub sub query works. Thank a ton !!!!
Just one strange detail: LIMIT in Subquery doesnt work when you test the result with IN or NOT IN. If you know you'll get only one result (so a sub query with LIMIT 1), you can do it. Just use "=" rather than "IN" and that's OK.
|
10

You can try this:

DELETE 
    p1.* 
FROM 
    posts p1 INNER JOIN 
    (SELECT 
            id 
    FROM 
            posts 
            ORDER BY timestamp DESC 
            LIMIT 0, 15
    ) AS p2 
ON p1.id = p2.id;

Comments

2

Since the newest 15 will always come from the first 15 if you order them by descending order.You can just delete any id that did not make it into the first 15. like so i just tried it and it worked fine. Hopefully it helps someone

Delete from `table` where id not in (SELECT * FROM (Select id from `table` order by id desc limit 15) as derivedTable);

1 Comment

That's basically the same the first answer proposed; circumventing the limitation by doing two (nested) subqueries. Also, sorting by id instead of timestamp is not reliable, as older entries with a lower id might get a newer timestamp for various reasons.

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.