从 MySQL 中选择最后 N 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12125904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select last N rows from MySQL
提问by nanobash
I want to select last 50 rows from MySQL database within column named idwhich is primary key. Goal is that the rows should be sorted by idin ASCorder, that's why this query isn't working
我想在名为id 的列中从 MySQL 数据库中选择最后 50 行,该列是主键。目标是行应该被分类ID在ASC秩序,这就是为什么这个查询不工作
SELECT
*
FROM
`table`
ORDER BY id DESC
LIMIT 50;
Also it's remarkable that rows could be manipulated (deleted) and that's why following query isn't working either
同样值得注意的是,可以操作(删除)行,这就是为什么以下查询也不起作用的原因
SELECT
*
FROM
`table`
WHERE
id > ((SELECT
MAX(id)
FROM
chat) - 50)
ORDER BY id ASC;
Question: How is it possible to retrieve last N rows from MySQL database that can be manipulated and be in ASC order ?
问题:如何从 MySQL 数据库中检索可操作且按 ASC 顺序排列的最后 N 行?
回答by newfurniturey
You can do it with a sub-query:
您可以使用子查询来做到这一点:
SELECT * FROM (
SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC
This will select the last50 rows from table
, and then order them in ascending order.
这将从 中选择最后50 行table
,然后按升序对它们进行排序。
回答by aidonsnous
SELECT * FROM table ORDER BY id DESC,datechat desc LIMIT 50
If you have a date field that is storing the date(and time) on which the chat was sent or any field that is filled with incrementally(order by DESC) or desinscrementally( order by ASC) data per row put it as second column on which the data should be order.
如果您有一个存储聊天发送日期(和时间)的日期字段,或者每行增量(按 DESC 排序)或减增量(按 ASC 排序)数据填充的任何字段,请将其作为第二列数据应该是有序的。
That's what worked for me!!!! hope it will help!!!!
这对我有用!!!!希望它会有所帮助!!!!
回答by Buzz
SELECT * FROM table ORDER BY id DESC LIMIT 50
save resources make one query, there is no need to make nested queries
节省资源 一键查询,无需嵌套查询
回答by Darshan
select * from Table ORDER BY id LIMIT 30
Notes:
* id
should be unique.
* You can control the numbers of rows returned by replacing the 30
in the query
注意: *id
应该是唯一的。* 可以通过替换30
查询中的来控制返回的行数