doouzlrvb01417498 2010-08-15 11:53
浏览 62
已采纳

在MySQL-Table中按日期获取最后一个和下一个db-record?

I've got a certain question related to a blog, which I am developing in OOP (PHP) right now. All blogposts are stored in a MySQL-table.

In the app you can read a specific post by giving the id of the post via GET-parameter. So like http://example.com/?id=2. Under the blogpost I want to show to navigation links like "previous" and "next", to see the next and previous blogpost ordered by date relative to the post the user is reading now. So what I need is the id of the next and the previous record in the mysql-table by date.

How to solve this? Is there any way to solve this in SQL, or do I have to get all records with php and then do some checks to determine if this is the last or next one?

Just a note: I don't want to fetch the last and next posts by id, but by date to get the id of them.

Any help would be appreciated. Thanks.

  • 写回答

2条回答 默认 最新

  • duanmanmian7589 2010-08-15 11:59
    关注

    To get the newest record older than a certain date:

    SELECT id
    FROM yourtable
    WHERE date < '2010-08-15 14:07:12'
    ORDER BY date DESC
    LIMIT 1
    

    Or the oldest record newer than a certain date:

    SELECT id
    FROM yourtable
    WHERE date > '2010-08-15 14:07:12'
    ORDER BY date 
    LIMIT 1
    

    Make sure that the date column is indexed.

    This works fine if date is unique, but if you have two records with exactly the same date and use next repeatedly this could skip over one of the records. To solve this you could use a tie-breaker column such that (date, tie-breaker) is always unique. You could for example use the primary key as a tie-breaker.

    See my answer to this question to see how to do this:

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

报告相同问题?

悬赏问题

  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改