mySQL subquery limit

Mysql

Mysql Problem Overview


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'

Mysql Solutions


Solution 1 - Mysql

Try this:

DELETE 
FROM posts 
WHERE id not in (
      SELECT * FROM (
            SELECT id 
            FROM posts 
            ORDER BY timestamp desc limit 0, 15
      ) 
      as t);

Solution 2 - Mysql

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;

Solution 3 - Mysql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndré Alçada PadezView Question on Stackoverflow
Solution 1 - MysqlNicola CossuView Answer on Stackoverflow
Solution 2 - MysqlErtugrul YilmazView Answer on Stackoverflow
Solution 3 - MysqlSamuel Kwame AntwiView Answer on Stackoverflow