使用2左连接无法工作,但可以单独获得结果

时间:2017-05-25 21:07:00

标签: mysql sql left-join

我有三张桌子,公司,用户和分享。我想算一个公司的用户和分享,他们不相关。

可能有一行具有共享值但不具有用户值。所以我使用左连接,我可以单独得到结果,但它不能一起工作。

这是我的问题:

SELECT c.name, count(u.company_id), count(s.company_id)
FROM company c
LEFT JOIN user u
ON c.id=u.company_id and u.company_id=337
WHERE u.company_id is NOT NULL 
LEFT JOIN share s
ON c.id=s.id AND s.company_id=337 
WHERE s.company_id is NOT NULL 

2 个答案:

答案 0 :(得分:1)

您需要在子查询中至少执行一个计数。否则,两个计数都是相同的,因为您只是计算得到的叉积中的行。

SELECT c.name, user_count, share_count
FROM company AS c
JOIN (SELECT company_id, COUNT(*) AS user_count
      FROM users
      GROUP BY company_id) AS u
ON u.company_id = c.id
JOIN (SELECT company_id, COUNT(*) AS share_count
      FROM share 
      GROUP BY company_id) AS s
ON s.company_id = c.id
WHERE c.company_id = 337

另一种选择是计算您加入的表的不同主键:

SELECT c.name, COUNT(DISTINCT u.id) AS user_count, COUNT(DISTINCT s.id) AS share_count
FROM company AS c
JOIN users AS u on u.company_id = c.id
JOIN share AS s ON s.company_id = c.id
WHERE c.company_id = 337

答案 1 :(得分:0)

除了额外的WHERE子句外,您的代码看起来还可以。但是,您可能需要COUNT(DISTINCT),因为这两个计数将返回相同的值:

SELECT c.name, count(distinct u.company_id), count(distinct s.company_id)
FROM company c LEFT JOIN
     user u
     ON c.id = u.company_id and u.company_id=337 LEFT JOIN
     share s
     ON c.id = s.id AND s.company_id=337 
WHERE s.company_id is NOT NULL AND u.company_id IS NOT NULL;