使用左连接的一对多计数在源 table 上给出了错误的计数

Count one-to-many using left join gives wrong count on source table

我有两个表 user_resultsuser_shares

user_results 有:

id - pk
platform - string
country - string
created_at - timestamp

user_shares 有:

id - pk
user_result_id - integer
created_at - timestamp

这是我的查询:

select 
    count(user_results.id) as results,
    count(user_shares.id) as shares,
    user_results.platform as platform 
from
    user_results
left join 
    user_shares on user_results.id = user_shares.user_result_id 
group by 
    platform

这是一个 sql fiddle 的模式和有问题的查询: http://sqlfiddle.com/#!9/739a3/2

现在,正如您在 fiddle 上看到的,我每个平台只有 1 个结果,但 results 计数显示(我猜)"results count without share + shares count"

我做错了什么?

您需要计算 distinct user_results.id,因为加入 table 会复制其行:

select 
  count(distinct user_results.id) as results,
  count(user_shares.id) as shares,
  user_results.platform as platform 
from
  user_results
left join 
  user_shares on user_results.id = user_shares.user_result_id 
group by 
  platform