简体   繁体   English

MySql得到10条最近的评论以及所有子评论

[英]MySql get 10 recent comments with all sub comments

I have a comment table like 我有一个评论表

id | post_id | parent_id | user_id | text | time | likes

Comments can have 1 level sub comments(no 2nd/3rd level nesting). 注释可以具有1级子注释(无2级/ 3级嵌套)。 Users can sort comments based on time/likes. 用户可以根据时间/喜欢来对评论进行排序。

What will be the query to get 10 recent comments along with all their sub comments . 获取10条最近的评论以及所有子评论的查询将是什么。

SELECT `id`, `user_id`, `text` 
FROM `comments` 
WHERE `post_id` = '$postId' OR `parent_id` IN 
(
   SELECT `id` FROM `comments` 
   WHERE `post_id` = '$postId' 
   ORDER BY `time` DESC 
   LIMIT 10
) 
ORDER BY `time` DESC 
LIMIT 10

This doesn't work. 这行不通。

Add other conditions as needed. 根据需要添加其他条件。

SELECT c.`id`, c.`parent_id`, c.`user_id`, c.`text` 
FROM `comments` c,
(
   SELECT `id` FROM `comments` 
   WHERE `post_id` = '$postId' 
   ORDER BY `time` DESC 
   LIMIT 10
) temp
where c.id = temp.id or c.parent_id=temp.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM