2016-09-04 59 views
1

许多2个多我有表/记录是这样的:ORDER BY子句中的MySQL

Table: COMMENTS 
--------------------------------------------- 
COMMENT_ID | CONTENT   | CREATE_DATE 
--------------------------------------------- 
     1 | Content 1   | 2016-09-01 
     2 | Content 2   | 2016-09-02 
     3 | Content 3   | 2016-09-03 
     4 | Reply to Content 2 | 2016-09-04 
     5 | Reply to Content 1 | 2016-09-05 
     6 | Reply to Content 2 | 2016-09-03 


Table: REPLY_COMMENTS 
--------------------------------- 
COMMENT_ID | REPLY_TO_COMMENT_ID 
--------------------------------- 
    4  |   2 
    5  |   1 
    6  |   2 

而且我想表明这样的顺序记录:

--------------------------------------------- 
COMMENT_ID | CONTENT   | CREATE_DATE 
--------------------------------------------- 
     1 | Content 1   | 2016-09-01 
     5 | Reply to Content 1 | 2016-09-05 
     2 | Content 2   | 2016-09-02 
     6 | Reply to Content 2 | 2016-09-03 
     4 | Reply to Content 2 | 2016-09-04 
     3 | Content 3   | 2016-09-03 

所以'回复“内容应该在父母的内容下 - 但回复内容也应该由CREATE_DATE定购。

基本上,我想放在一起:内容和CREATE_DATE的顺序回复。

我写这样的查询:

SELECT comment.* 
FROM COMMENTS comment 
LEFT JOIN REPLY_COMMENTS reply_comment ON reply_comment.COMMENT_ID = comment.COMMENT_ID 

ORDER BY (SOMETHING SHOULD BE HERE), comment.CREATE_DATE ASC 

我不能用我目前的知识写order by子句 - 请帮我(我使用MySQL)。

只希望使用COMMENTS.CREATE_DATE场 - 不想使用COMMENT_ID领域,因为它的主键(它甚至有可能?)。

回答

2
SELECT t1.COMMENT_ID, 
     t1.CONTENT, 
     t1.CREATE_DATE 
FROM COMMENTS t1 
LEFT JOIN REPLY_COMMENTS t2 
    ON t1.COMMENT_ID = t2.COMMENT_ID 
ORDER BY COALESCE(t2.REPLY_TO_COMMENT_ID, t1.COMMENT_ID), 
     t1.CREATE_DATE 

说明:

ORDER BY子句使用订货两届。第一个COALESCE条款将返回父消息的COMMENT_ID(父母和单身后代子女)。这样做的原因是,对于孩子来说,它将使用加入的ID,对于父母来说,如果找到NULL,它也会默认使用父ID。第二个排序术语使用创建日期,假设所有对帖子的回复都会在原帖之后发生。