从MySQL中选择最后N行 [英] Select last N rows from MySQL

查看:136
本文介绍了从MySQL中选择最后N行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从名为 id 的列中的主键中选择MySQL数据库中的最后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数据库检索最后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 ,然后按升序排序。

This will select the last 50 rows from table, and then order them in ascending order.

这篇关于从MySQL中选择最后N行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆