【问题标题】:MySQL timestamp comparison with less than signMySQL时间戳比较小于号
【发布时间】:2012-08-07 06:01:01
【问题描述】:

我做了一个 PHP 博客。除了一个小故障,一切都正常运行。我想按日期降序显示文章。因此,每当一篇文章被添加到数据库中时,自动时间戳都会记录插入的时间。

GLITCH -> 我想每页显示 5 篇文章。通过使用这个,我很容易在第一页上做到了这一点

$sql="SELECT id,article_name,article_body,date 
         from articles order by date desc limit 5" ;

现在我想继续第二页,并希望第二页显示第 1 页离开的文章。如果有 10 篇文章按降序排列,第 1 页应显示前 5 篇,第 2 页应显示后 5 篇。

当每天添加许多文章时,此逻辑应该实时工作。我使用了这个查询,但它只显示 1 行。

$sql="select id,article_name,article_body,unix_timestamp(date) 
           from articles 
           where date < (select unix_timestamp(date)
                 from articles order by date desc limit $n,1 ) 
           order by date desc limit $n,5" ;

$n - 从中​​提取行的 id。

【问题讨论】:

  • 您必须将“最后一篇文章 id”放在“下一页”链接中,否则无法知道从哪里开始。
  • 我认为 sel 的解决方案是最好的。 limit+offset 为您处理分页,您无需指定从哪里开始。但是如果你使用&lt; (subquery),那么你不应该在外部查询中指定$n——小于已经处理了你离开的地方,额外的$n会导致它跳过两倍的数字。跨度>

标签: php mysql sql timestamp blogs


【解决方案1】:

利用sql中的偏移量:

$items_per_page=5;   
$offset=($current_page-1)* $items_per_page;

sql:

SELECT id,article_name,article_body,date 
         from articles order by date desc LIMIT  $items_per_page OFFSET $offset

【讨论】:

  • 嗯....但我想根据日期对文章进行排序。就像最新的文章在前,旧的文章在后。
  • @barmer man,您的建议对我帮助很大!谢谢一个人!
【解决方案2】:

尝试:

select id,article_name,article_body,unix_timestamp(date) 
from articles 
where date < ( select date from articles order by date desc limit $n,1 ) 
order by date desc limit $n,5

$n 应该是上一页的最后一个 id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    相关资源
    最近更新 更多