简体   繁体   中英

SELECT all but the last 5 items in MySQL

I'm trying to run a query that will SELECT all but the 5 items in my table.

I'm currently using the following query to get the last 5 items.
SELECT * FROM articles ORDER BY id DESC LIMIT 5

And I would like another query to get all the other items, so excluding the last 5.

You select the last 5 items by conveniently sorting them in the reverse order.

SELECT * FROM articles ORDER BY id DESC LIMIT 5

LIMIT 5 is, in fact, a short form of LIMIT 0, 5 .

You can use the same trick to skip the first 5 items and select the rest of them:

SELECT * FROM articles ORDER BY id DESC LIMIT 5, 1000000

Unfortunately MySQL doesn't provide a way to get all the rows after it skips the first 5 rows. You have to always tell it how many rows to return. I put a big number (1 million) in the query instead.

For both queries, the returned articles will be sorted in the descending order. If you need them in the ascending order you can save the smallest value of id returned by the first query and use it in the second query:

SELECT * FROM articles WHERE id < [put the saved id here] ORDER BY id ASC

There is no need for limit on the second query and you can even sort the records by other columns if you need.

You can do it like this:

SELECT * FROM articles
ORDER BY id ASC
LIMIT (SELECT count(*)-5 FROM articles)

You can also use NOT EXISTS() or NOT IN() but I'll have to see the columns names to adjust the sql for you, something like this:

SELECT * FROM articles a
WHERE a.id NOT IN(SELECT id FROM articles ORDER BY id DESC LIMIT 5)

Can also be done with a left join:

SELECT t.* FROM articles t
LEFT JOIN (SELECT id FROM articles ORDER BY id DESC LIMIT 5) s
 ON(t.id = s.id)
WHERE s.id is null

Note that if the table has more then one key(the ID column) you have to add it to the relations of the ON clause.

尝试

SELECT * FROM articles a NOT  EXIST (SELECT * FROM articles b WHERE a.id=b.id ORDER BY id DESC LIMIT 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM