2016-09-04 60 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。第二個排序術語使用創建日期,假設所有對帖子的回覆都會在原帖之後發生。