Select last N rows from MySQL(从 MySQL 中选择最后 N 行)
问题描述
我想从 MySQL 数据库中选择名为 id 的列中的最后 50 行,该列是主键.目标是行应该按照 ASC 顺序按 id 排序,这就是此查询不起作用的原因
I want to select last 50 rows from MySQL database within column named id which is primary key. Goal is that the rows should be sorted by id in ASC order, that’s why this query isn’t working
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;
问题:如何从 MySQL 数据库中检索可操作且按 ASC 顺序排列的最后 N 行?
Question: How is it possible to retrieve last N rows from MySQL database that can be manipulated and be in ASC order ?
推荐答案
您可以使用子查询来实现:
You can do it with a sub-query:
SELECT * FROM (
SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC
这将从table中选择最后 50行,然后按升序排列.
This will select the last 50 rows from table, and then order them in ascending order.
这篇关于从 MySQL 中选择最后 N 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 MySQL 中选择最后 N 行
基础教程推荐
- 在多列上分布任意行 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- oracle区分大小写的原因? 2021-01-01
