以下查询效果很好。它根据s.points
将结果分为两个层次。
s.datesubmitted
的所有结果。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";
答案 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
在这种情况下:
points DESC
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