MySQL中Many 2 Many的Order by子句
我有这样的表格/记录:MySQL中Many 2 Many的Order by子句,mysql,sql,sql-order-by,Mysql,Sql,Sql Order By,我有这样的表格/记录: Table: COMMENTS --------------------------------------------- COMMENT_ID | CONTENT | CREATE_DATE --------------------------------------------- 1 | Content 1 | 2016-09-01 2 | Content 2 | 2016-
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
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
我想展示如下顺序的记录:
---------------------------------------------
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
因此,“回复”内容应该在父级内容下,但回复内容也应该按创建日期排序
基本上,我想把内容和回复放在一起,按创建日期的顺序排列
我这样写查询:
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
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
以我目前的知识,我无法编写ORDERBY子句-请帮助我(我正在使用MySQL)
我只想使用注释。创建日期
字段-不想使用注释ID
字段,因为它是主键(可能吗?)
说明:
orderby
子句使用两个术语进行排序。第一个COALESCE
术语将返回父消息的COMMENT\u ID
(对于父消息和单后代子消息)。这样做的原因是,对于孩子,它将使用加入的ID;对于家长,如果发现NULL,它也将默认为家长ID。第二个排序术语使用创建日期,前提是对帖子的所有回复都将发生在原始帖子之后