1

我有一个评论表,其中包含具有以下字段的父子评论

comments
    comment_id
    parent_id
    thread_id (Foreign Key)
    title
    body
    comment_date
    user_name

我想整理这种形式的评论,首先出现父评论,然后是子评论,然后是下一个父评论,然后是子评论

我正在使用以下查询

SELECT c1 . * , c2 . * 
FROM comments c1
LEFT JOIN comments c2 ON c2.parent_id = c1.comment_id
WHERE c1.parent_id IS NULL 
AND c1.thread_id =122

它给出以下输出 在此处输入图像描述

可以看到第一个表中有很多重复的行

我想要以下输出

在此处输入图像描述

你可以看到,在这个输出中,首先是父评论(在 parent_id 中有 NULL),然后是它的子评论,然后是下一个父评论,然后是它的子评论。

我怎样才能形成我的 SQL 查询来获得这个输出。注意:(第二张图不是任何查询的结果,我已经修改了它只是为了澄清我的观点并告诉你我想要什么样的输出。)

4

3 回答 3

3

没有一行是重复的,只是c1评论被反复选择,因为它表面上是许多c2评论的父级。听起来您实际上想要两个单独的查询。

SELECT * FROM comments WHERE parent_id IS NULL AND thread_id = 122
UNION
SELECT c2.* FROM comments c1 JOIN comments c2 ON c2.parent_id = c1.comment_id
WHERE c1.parent_id IS NULL AND c1.thread_id =122
于 2013-04-10T07:08:44.713 回答
0
SELECT c1 . * , c2 . * 
FROM comments c1
LEFT JOIN comments c2 ON c2.parent_id = c1.comment_id
WHERE c2.parent_id IS NOT NULL 
AND c1.thread_id = 122

I created table and tested with the above query ,it works fine for me.If the above doesn't work fine for you,then please export the comment table and post here .I'll send the exact query.

Once again ,if it is in cakephp, then use 'threaded' in the find query ,which always works fine for parent-child type table structure in database.

Waiting for the response...

于 2013-04-10T07:53:23.010 回答
0
SELECT c1 . *
FROM comments c1
RIGHT JOIN comments c2 ON c2.parent_id = c1.comment_id
WHERE c1.parent_id IS NULL 
AND c1.thread_id =122
于 2013-04-10T07:17:39.540 回答