0

我正在运行 SQL 查询,它的作用是为论坛服务。首先它将问题加入他们的答案,然后检查帖子是否具有粘性,在这种情况下,它不是,然后按 id 分组(不知道为什么这是必要的,我从网站上得到了这部分),最后订购它们。我希望它们如何被订购,首先是日期/时间,然后如果有人回复,它将转到顶部。例如:

Post: 2 Replies: 1 Last Post: 10:00PM First Post: 9:00PM
Post: 3 Replies: 0 Last Post: 9:30PM  First Post: 9:30PM
Post: 1 Replies: 0 Last Post: 8:00PM  First Post: 8:00PM

这是返回的地方:

Post: 3 Replies: 0 Last Post: 9:30PM  First Post: 9:30PM
Post: 2 Replies: 1 Last Post: 10:00PM First Post: 9:00PM
Post: 1 Replies: 0 Last Post: 8:00PM  First Post: 8:00PM

这是实际的查询:

SELECT * 
FROM forum_question
LEFT JOIN forum_answer ON ( forum_question.id = forum_answer.question_id ) 
WHERE category =  '7'
AND  `sticky` =0
GROUP BY forum_question.id
ORDER BY CASE WHEN reply >0
THEN a_datetime
WHEN reply =0
THEN DATETIME
END DESC 

样本数据:

ID; Topic; Name; Detail; Datetime; Reply; Category; Sticky;
1; Post 1; Demo; Detail; 07/09/13, 9:00; 0; 7; 0;
2; Post 2; Demo; Detail; 07/09/13, 9:15; 0; 7; 0;
3; Post 3; Demo; Detail; 07/09/13, 9:30; 2; 7; 0;
4; Post 4; Demo; Detail; 07/09/13, 9:45; 0; 7; 0;

Question_ID; A_ID; A_Name; A_Detail; Datetime; 
3; 1; Demo1; Detail; 07/09/13, 9:31;
3; 2; Demo1; Detail; 07/09/13, 9:46;
4

1 回答 1

0

尝试

SELECT * 
  FROM forum_question LEFT JOIN forum_answer 
    ON forum_question.id = forum_answer.question_id
 WHERE category =  '7'
   AND  `sticky` =0
 GROUP BY forum_question.id
 ORDER BY (reply = 0),
       CASE WHEN reply > 0 THEN a_datetime
            ELSE datetime
       END DESC 
于 2013-09-08T03:05:34.740 回答