ORDER BY / CASE 组合导致 MySQL 查询不起作用
下面的查询返回一个空白页。这是由 ORDER BY 和 CASE 组合引起的,因为查询的其余部分可以很好地处理不太复杂的内容。
有谁看到这部分有任何明显的错误:
ORDER BY CASE
WHEN s.datesubmitted > DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN s.points
WHEN s.datesubmitted < DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN most_recent
END, DESC
代码:
$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 s.points
WHEN s.datesubmitted < DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN most_recent
END, DESC
LIMIT $offset, $rowsperpage";
The query below is returning a blank page. It's caused by the ORDER BY and CASE combination, because the rest of the query works fine with something less complicated.
Does anyone see any glaring errors in this part:
ORDER BY CASE
WHEN s.datesubmitted > DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN s.points
WHEN s.datesubmitted < DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN most_recent
END, DESC
Code:
$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 s.points
WHEN s.datesubmitted < DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN most_recent
END, DESC
LIMIT $offset, $rowsperpage";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很确定
END
和DESC
之间的逗号不正确。如果您担心ORDER BY
使语法混乱,您可以尝试将整个CASE
表达式括在括号中。我会把这个大的令人困惑的表达式放在选择列表中,然后就按顺序排序,但是?有什么原因让你绝对不能更改选择列表吗?
Pretty sure the comma between
END
andDESC
is not correct. You might try wrapping the wholeCASE
expression in parentheses, if you're worried thatORDER BY
is getting the syntax confused.I would put this large confusing expression in the select list and just order on that, though? Is there a reason you definitely can't change the select list?
您希望在“case”语句后不加逗号:
或者,为了更好地理解它,您可以用括号将其括起来...
...所以它就像一列,然后在其后面放置“DESC”关键字指定您要按降序排列..(不需要逗号)
You want it without the comma after your 'case' statement:
Or, to understand it better, you could possibly surround it with parens...
...so it's like a column, and then you put the 'DESC' keyword after it designate that you want to order in descending order.. (no comma needed)