Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

sql - How to make comment reply query in MYSQL?

I am having comment reply (only till one level) functionality. All comments can have as many as replies but no replies can have their further replies.

So my database table structure is like below

Id    ParentId    Comment
1     0           this is come sample comment text
2     0           this is come sample comment text
3     0           this is come sample comment text
4     1           this is come sample comment text
5     0           this is come sample comment text
6     3           this is come sample comment text
7     1           this is come sample comment text

In the above structures, commentid, 1 (has 2 replies) and 3 (1 reply) has replies. So to fetch the comments and their replies, one simple method is first I fetch all the comments having ParentId as 0 and then by running a while loop fetch all the replies of that particular commentId. But that seems to be running hundreds of queries if I'll have around 200 comments on a particular record.

So I want to make a query which will fetch Comments with their replies sequentially as following;

Id    ParentId    Comment
1     0           this is come sample comment text
4     1           this is come sample comment text
7     1           this is come sample comment text
2     0           this is come sample comment text
3     0           this is come sample comment text
6     3           this is come sample comment text    
5     0           this is come sample comment text

I also have a comment date column in my comment table, if anyone wants to use this with comment query.

So finally I want to fetch all the comments and their replies by using one single mysql query. Please tell me how I can do that?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use an expression in an ORDER BY. Try this:

SELECT *
FROM comments
ORDER BY IF(ParentId = 0, Id, ParentId), Id

This will first sort by Id, if ParentId = 0, or by ParentId otherwise. The second sort criterion is the Id, to assure that replies are returned in order.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...