根据时间戳字段的年龄来排序MySQL查询

时间:2011-05-19 02:37:10

标签: php mysql sql

对于下面的查询,我按ORDER BY s.points DESC订购,这工作正常。但我想更改它,以便s.points仅在s.datesubmitted在最后一小时内降序。字段s.datesubmitted是时间戳。否则,我想按most_recent降序排序。

我怎么能这样做?

提前致谢,

约翰

 $sqlStr = "SELECT s.loginid, s.title, s.url, s.displayurl, s.points, s.datesubmitted, l.username,
           s.submissionid, s.subcheck, s.topten, COUNT(c.commentid) countComments, 
           GREATEST(s.datesubmitted, COALESCE(MAX(c.datecommented), s.datesubmitted)) AS most_recent
      FROM submission s
      JOIN login l ON s.loginid = l.loginid
 LEFT JOIN comment c ON s.submissionid = c.submissionid
  GROUP BY s.submissionid
  ORDER BY s.points DESC 

     LIMIT $offset, $rowsperpage";

2 个答案:

答案 0 :(得分:0)

我会使用日期函数,如sub / add等。(mysql函数) http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff

$sqlStr = "SELECT s.loginid, s.title, s.url, s.displayurl, s.points, s.datesubmitted, l.username,
           s.submissionid, s.subcheck, s.topten, COUNT(c.commentid) countComments, 
           GREATEST(s.datesubmitted, COALESCE(MAX(c.datecommented), s.datesubmitted)) AS most_recent
      FROM submission s
      JOIN login l ON s.loginid = l.loginid
 LEFT JOIN comment c ON s.submissionid = c.submissionid
  GROUP BY s.submissionid

  ORDER BY s.points DESC, s.datesubmitted DESC
     WHERE s.datesubmitted > DATE_SUB(NOW(), INTERVAL 1 HOUR)

     LIMIT $offset, $rowsperpage";

我无处可测试它。

答案 1 :(得分:0)

MySQL允许ORDER BY子句中的表达式。

...
ORDER BY (CASE WHEN s.submitted > DATE_SUB(NOW(), INTERVAL 1 HOUR) 
  THEN s.points ELSE GREATEST(s.datesubmitted, 
                        COALESCE(MAX(c.datecommented), s.datesubmitted)) END) DESC;

如果我怀疑你真的想要最后一小时的第一个小时,然后是不同排序的陈旧小时,请在此之前添加另一个ORDER BY变量,

(CASE WHEN s.submitted > DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 ELSE 0 END)

并对DESC进行排序。