如何使用JOIN从两个表中计数

时间:2014-06-22 15:10:24

标签: mysql

我正在做Q& A项目,所以我有三个相关的表。 我想列出所有计算所有最佳答案的用户。 下面是我的表和SQL

问题

id          | bestanswerid (index from table answer)
-----------------------
1           | 10
2           | 23
3           | 124
..          | ..

回答

id          | userid (index from table user)
-----------------------
1           | 1
2           | 5
3           | 1
..          | ..

SQL

SELECT user.*, (SELECT COUNT(*) AS best_answer_count
FROM answer WHERE answer.id IN (
    SELECT bestanswerid 
    FROM question WHERE question.bestanswerid = answer.id
) AND answer.userid = user.id)
FROM user;

它的工作但看起来很慢,我想使用JOIN但却感到困惑 请帮助或建议我,谢谢。

2 个答案:

答案 0 :(得分:0)

如果你只想要名字和计数

,你可以做一个简单的内连接
SELECT
     U.id,
     COUNT(BAC.bestanswerid)
FROM user U
INNER JOIN BAC
   ON U.id = BAC.userid;

答案 1 :(得分:0)

试试:

 SELECT user.*, COUNT(*) AS best_answer_count
 FROM answer
 LEFT JOIN user ON  answer.userid = user.id 
 LEFT JOIN question ON question.bestanswerid = answer.id 
 GROUP BY user.id

simple fiddle