【问题标题】:MySQL: Select comments and the number of replies they haveMySQL:选择评论和他们的回复数量
【发布时间】:2010-12-14 18:27:21
【问题描述】:

我有一个“评论”MySQL 表,其中包含以下字段:

  • 身份证
  • 文字
  • parent_id(默认为 NULL)

基本上我想选择所有具有 NULL parent_id 的 cmets,以及他们的回复总数。这个评论系统只有一级回复。结果看起来像:

-------------------------------------------------
| id | Text                     | total_replies |
-------------------------------------------------
| 1  | This is a comment        | 0             |
-------------------------------------------------
| 5  | another comment          | 3             |
-------------------------------------------------
| 7  | a different comment      | 1             |
-------------------------------------------------

感谢您的帮助:)

【问题讨论】:

    标签: mysql


    【解决方案1】:

    这可能是这样的:

    select c.id, c.Text, count(reply.id) as total_replies
    from comments c 
    left join comments reply on c.id = reply.parent_id
    where c.parent_id is null
    group by c.id
    

    如果我正确理解 cmets 和回复在同一个表中。

    【讨论】:

      【解决方案2】:

      假设回复在同一个表中:

      SELECT c1.id, c1.text, COUNT(c2.id) total_replies
      FROM comments c1 
      LEFT JOIN comments c2 ON c2.parent_id = c1.id
      WHERE c1.parent_id IS NULL
      GROUP BY c1.id, c1.text
      ORDER BY c1.id
      

      【讨论】:

      • c1.parent_id = c2.idc1.parent_id is NULL 怎么可能?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 2019-08-07
      • 2021-03-14
      • 1970-01-01
      相关资源
      最近更新 更多