MySQL ORDER BY,CASE基于每个案例的不同字段

时间:2011-05-20 03:36:04

标签: php mysql

以下查询效果很好。它根据s.points将结果分为两个层次。

  • 第1层:过去一小时内s.datesubmitted的所有结果。
  • 第2层:1小时前s.datesubmitted的所有结果。

第1层的结果优先于第2层。因此,在过去一小时内提交的任何内容都会显示在一小时前提交的任何内容之上,而不管s.points

第2层的结果是1小时前提交的所有项目。与第1层一样,它们按s.points排序。我如何在s.points之前订购第1层,但是按most_recent订购第2层?

提前致谢,

约翰

   $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 
        CASE 
                 WHEN s.datesubmitted > DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 0 
                 WHEN s.datesubmitted > DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1
                 ELSE 2 
               END, s.points DESC

         LIMIT $offset, $rowsperpage";

2 个答案:

答案 0 :(得分:0)

ORDER BY CASE 
             WHEN s.datesubmitted >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN CONCAT(1, ',', s.points)
             WHEN s.datesubmitted < DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN CONCAT(0, ',', s.datesubmitted)
         END DESC

在这种情况下:

  • 第1层:一小时内的所有记录将按points DESC
  • 排序
  • 第2层:所有其他记录按datesubmitted DESC(最近的)
  • 排序

答案 1 :(得分:0)

SELECT
  loginid, title, url, displayurl, points, datesubmitted, username,
  submissionid, subcheck, s.topten, countComments, most_recent
FROM (
  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,
    s.datesubmitted > DATE_SUB(NOW(), INTERVAL 1 HOUR) AS is_within_hour
  FROM submission s
    INNER JOIN login l ON s.loginid = l.loginid
    LEFT JOIN comment c ON s.submissionid = c.submissionid
  GROUP BY s.submissionid
) x
ORDER BY
  is_within_hour DESC,
  CASE WHEN     is_within_hour THEN points        END DESC,
  CASE WHEN NOT is_within_hour THEN datesubmitted END DESC
LIMIT $offset, $rowsperpage