从 MySQL 中选择最后 N 行

Select last N rows from MySQL(从 MySQL 中选择最后 N 行)
本文介绍了从 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 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)