MYSQL Left Join COUNTS from multiple tables

前端 未结 1 1494
谎友^
谎友^ 2020-12-02 10:06

I want to add columns that represent counts from other tables.

I have 3 tables.

Messages

MessageID    User      Message            


        
相关标签:
1条回答
  • 2020-12-02 10:37
    select
      t.Topic,
      t.Title,
      count(distinct s.starID) as StarCount,
      count(distinct m.User) as UserCount,
      count(distinct m.messageID) as MessageCount
    from
      Topics t
      left join Messages m ON m.Topic = t.Topic
      left join Stars_Given s ON s.Topic = t.Topic
    group by
      t.Topic,
      t.Title
    

    Sql Fiddle

    Or, you can perform the aggregation in sub-queries, which will likely be more efficient if you have a substantial amount of data in the tables:

    select
      t.Topic,
      t.Title,
      s.StarCount,
      m.UserCount,
      m.MessageCount
    from
      Topics t
      left join (
        select 
          Topic, 
          count(distinct User) as UserCount,
          count(*) as MessageCount
        from Messages
        group by Topic
      ) m ON m.Topic = t.Topic
      left join (
        select
          Topic, 
          count(*) as StarCount
        from Stars_Given 
        group by Topic
      ) s ON s.Topic = t.Topic
    

    Sql Fiddle

    0 讨论(0)
提交回复
热议问题