MySQL 来自多个表的MYSQL左连接计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15349189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:51:47  来源:igfitidea点击:

MYSQL Left Join COUNTS from multiple tables

mysqlcountleft-join

提问by Tom

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

我想添加表示来自其他表的计数的列。

I have 3 tables.

我有3张桌子。

Messages

消息

MessageID    User      Message      Topic
1            Tom       Hi           ball
2            John      Hey          book
3            Mike      Sup          book
4            Mike      Ok           book

Topics

话题

Topic      Title     Category1    Category2
ball       Sports    Action       Hot
book       School    Study        Hot

Stars_Given

Stars_Given

starID     Topic
1          ball
2          book
3          book
4          book

I want to end up with:

我想结束:

Topic_Review

主题_评论

Topic    Title     StarCount    UserCount    MessageCount
ball     Sports    1            1            1
book     school    3            2            3

So basically I want to attach 3 columns with counts of unique values (number of stars given within each topic, unique users who have messages within topic, and the number of unique messages in each topic).

所以基本上我想附加 3 列,其中包含唯一值的计数(每个主题中给出的星数、主题内有消息的唯一用户以及每个主题中的唯一消息数)。

I want to eventually be able to filter on the categories (look in both columns) as well.

我希望最终也能够过滤类别(查看两列)。

Also, I want to eventually sort by the counts that I join. Example, I'm going to have a button that sorts by "number of stars" by ascending order, or sort by "number of users" by descending order, etc.

另外,我想最终按我加入的计数进行排序。例如,我将有一个按钮,按升序按“星数”排序,或按降序按“用户数”排序,等等。

I've tried adapting other people's answers and I can't get it to work properly.

我试过调整其他人的答案,但无法正常工作。

回答by Michael Fredrickson

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

Sql小提琴

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

Sql小提琴