dongren9966 2016-04-01 01:23
浏览 396
已采纳

获取最后x条记录的最佳方法是什么? 使用MySQL Limit和ORDER DESC?

I was wondering if there are any other best/better practices then this as far as performance or optimizations.

EDIT: I'm using PHP7. Should have made that clear, I apologize. I'm doing a volunteer project for a local non-profit and it's setup like this:

Table: Volunteer

pk: v_id

So what I'm doing is: SELECT * from Volunteer ORDER BY v_id DESC LIMIT 25;

(They want the last 25 to display currently for the "last logs" report.)

EDIT2: The only reason I'm asking this now, we've hit 10k volunteer logs in the system and I'm starting to realize MON-FRI they can add anywhere from 50-100 (or more) logs per day so it quickly adds up.

  • 写回答

2条回答 默认 最新

  • dsaxw4201 2016-04-01 01:27
    关注

    If you can do it programatically ORDER it ASC with LIMIT X and then loop through the records backwards.

    If you give us your language (PHP, node(javascript), java, etc) we can help you with the backwards loop, but it goes something like this :

    for(i=rows.length-1;i>=0;i--){
       //do your stuff here
    }
    

    If you MUST do it in MySQL

    SELECT your results ASC with LIMIT X as a subquery and then wrap in a query ORDER DESC

    SELECT
    *
    FROM
    (
        SELECT
        somecol
        FROM
        sometable
        ORDER BY
        the_date ASC
        LIMIT 100
    ) as a
    ORDER BY
    the_date DESC
    

    UPDATE: The way the question was asked at first it sounded like you wanted the last X results, ordered DESC. I will leave my answer in place in case anyone else comes here looking for that.

    What you are doing now with the ORDER BY and LIMIT is the optimal way to do it. To optimize, you may want to SELECT only the columns you need, and make sure you have a unique index on v_id. If you need more optimization than that, you may want to consider archiving old data and vacuuming frequently.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵