【问题标题】:Select all categories with topic and post count选择具有主题和帖子计数的所有类别
【发布时间】:2014-09-24 12:09:46
【问题描述】:

我有id 的类别,idcategory 的主题,以及idtopic 的帖子。我想列出类别以及属于每个类别的主题数量以及属于这些类别的主题的帖子数量。

到目前为止,我使用什么来收集类别及其各自的主题计数

select c.*, count(t.id) topics
    from categories c
    join topics t
        on t.category=c.id
    group by c.id

我尝试了以下方法,但它只是给了我相同的帖子和主题数

select c.*, count(t.id) topics, count(p.id) posts
    from categories c
    join topics t
        on t.category=c.id
    join posts p
        on p.topic=t.id
    group by c.id

尝试left join 似乎没有任何区别

【问题讨论】:

    标签: mysql


    【解决方案1】:

    使用COUNT(DISTINCT t.id) 仅计算每个类别的唯一主题 ID。

    select c.*, count(DISTINCT t.id) topics, count(p.id) posts
    from categories c
    join topics t
        on t.category=c.id
    join posts p
        on p.topic=t.id
    group by c.id
    

    或者,您可以使用子查询:

    select c.*, 
       count(t.id) topics, 
       (   select count(p.id) 
           from posts p 
           where p.topic = t.id
       ) posts
    from categories c
    join topics t
        on t.category=c.id
    group by c.id
    

    甚至

    select c.*, 
    
       (  select count(t.id) 
          from topics t 
          where t.category = c.id) topics,
    
       (  select count(p.id) 
          from topics t 
          join posts p 
              on p.topic = t.id
          where t.category = c.id) posts
    from categories c
    

    在这种特殊情况下count(distinct) 显然是最简单的,但在其他情况下,子查询可以为您提供更多可能性。

    【讨论】:

    • 谢谢!但如果我知道你会这么说,我就不会添加关于子查询的整章。 ;-)
    猜你喜欢
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多