如何组合两个LEFT JOINS而不进行交叉?

时间:2014-03-10 21:26:01

标签: sql sqlite

我有两个问题需要合并为一个,但是当我这样做时,请继续获得矩阵效果。

SELECT u.*, COUNT(q.id) FROM users u LEFT JOIN questions q ON u.id = q.author_id GROUP BY u.id

SELECT u.*, COUNT(a.id) FROM users u LEFT JOIN answers a ON u.id = a.author_id GROUP BY u.id

这些查询本身给我10个问题和10个答案。 当我像下面这样组合它们时,问题和答案计数会跳到100个。

SELECT u.*, COUNT(q.id), COUNT(a.id) FROM users u LEFT JOIN questions q ON u.id = q.author_id LEFT JOIN answers a ON u.id = a.author_id GROUP BY u.id

2 个答案:

答案 0 :(得分:3)

您只需要为计数添加不同

SELECT u.*, COUNT(DISTINCT q.id), COUNT(DISTINCT a.id)
 FROM users u
 LEFT JOIN questions q ON u.id = q.author_id
 LEFT JOIN answers a ON u.id = a.author_id
 GROUP BY u.id

Here's a demo使用Data.SE

进行操作

或者,您可以在from子句中使用内联视图

SELECT u.*, q.QuestionCount, a.AnswerCount
FROM   users u 
       LEFT JOIN (SELECT Count(id) QuestionCount, 
                         author_id 
                  FROM   questions 
                  GROUP  BY author_id) q 
              ON u.id = q.author_id 
       LEFT JOIN (SELECT Count(id) AnswerCount, 
                         author_id 
                  FROM   answers 
                  GROUP  BY author_id) a 
              ON u.id = q.author_id 

Demo

答案 1 :(得分:1)

您可以使用相互独立的相关子查询替换连接:

SELECT *,
       (SELECT COUNT(*) FROM questions WHERE author_id = u.id),
       (SELECT COUNT(*) FROM answers   WHERE author_id = u.id)
FROM users u