简体   繁体   English

选择MySQL中除了最后5项之外的所有项目

[英]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. 我正在尝试运行一个查询,它将SELECT除表格中的5个项目以外的所有项目。

I'm currently using the following query to get the last 5 items. 我目前正在使用以下查询来获取最后5个项目。
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. 我想要另一个查询来获取所有其他项目,因此排除最后5项。

You select the last 5 items by conveniently sorting them in the reverse order. 您可以通过方便地按相反顺序对它们进行排序来选择最后5个项目。

SELECT * FROM articles ORDER BY id DESC LIMIT 5

LIMIT 5 is, in fact, a short form of LIMIT 0, 5 . LIMIT 5 ,实际上,短形式LIMIT 0, 5

You can use the same trick to skip the first 5 items and select the rest of them: 您可以使用相同的技巧跳过前5个项目并选择其余项目:

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. 不幸的是,MySQL在跳过前5行后没有提供获取所有行的方法。 You have to always tell it how many rows to return. 您必须始终告诉它要返回多少行。 I put a big number (1 million) in the query instead. 我在查询中添加了一个大数字(100万)。

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: 如果您需要升序,则可以保存第一个查询返回的最小id值,并在第二个查询中使用它:

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: 你也可以使用NOT EXISTS()NOT IN()但我必须看到列名来为你调整sql,如下所示:

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. 请注意,如果表有多个键(ID列),则必须将其添加到ON子句的关系中。

尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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