Sql计数返回错误的数字

时间:2014-09-30 09:45:56

标签: mysql sql left-join

我有一个api,我打电话给我,我需要很多来自不同表的数据,所以我使用连接,现在的问题是,虽然我有4个回复,5个交互数据总是返回20个回复和20相互作用就是结果:

screen_name screen_state replies interactions alerts
sjerd       0            20      20           0

我使用此查询来计算记录和结果:

   SELECT u.screen_name,
          u.screen_state,
          count(r.id) AS replies,
          count(i.id) AS interactions,
          count(a.alerts) AS alerts
   FROM   users u 
   LEFT   JOIN reply r ON u.id = r.user 
   LEFT   JOIN interactions i ON u.id = i.user_id 
   LEFT   JOIN alerts a ON u.id = a.user_id WHERE u.id ='2' 
   GROUP  BY u.id, u.screen_state

有人可以看到为什么它会返回20,而我在回复表中总共只有7行回复, 交互表中共有5行交互。 每一行都是1个反应或回复。

2 个答案:

答案 0 :(得分:3)

您的计数总是会产生相同的结果,因为所有表都在同一级别加入。

您需要将您的计数作为内联子查询(或其他任何 - 我永远不会记住正确的术语):

SELECT u.screen_name,
       u.screen_state,
       (select count(*) from reply r where u.id = r.user) AS replies,
       (select count(*) from interactions i where u.id = i.user_id) AS interactions,
       (select count(*) from alerts a where u.id = a.user_id) AS alerts
FROM   users u
WHERE u.id ='2' 

答案 1 :(得分:0)

   SELECT u.screen_name, u.screen_state, 
   count(DISTINCT r.id) AS replies,
   count(DISTINCT i.id) AS interactions,
   count(DISTINCT a.alerts) AS alerts 
   FROM users u 
   LEFT JOIN reply r ON u.id = r.user 
   LEFT JOIN interactions i ON u.id = i.user_id 
   LEFT JOIN alerts a ON u.id = a.user_id WHERE u.id ='2' 
   GROUP BY u.id, u.screen_state