使用mysql中的group子句连接count表

时间:2015-11-26 15:59:11

标签: mysql sql

我有3张桌子:

  • 申请(有很多票)
  • 投票(属于申请和问题)
  • 问题(有很多选票)

我需要为每个问题获得每个申请的投票数。

所以,我的尝试是:

SELECT applications.id, COUNT(votes.id), votes.question_id
FROM applications
LEFT OUTER JOIN votes ON (votes.application_id = application.id)
GROUP BY votes.question_id

但是,它仅显示单个应用程序的数据,因此我认为我的查询格式错误:

+----+-----------------+-------------+
| id | COUNT(votes.id) | question_id |
+----+-----------------+-------------+
|  1 |            1185 |           1 |
|  1 |            1170 |           2 |
|  1 |            1209 |           3 |
|  1 |            1230 |           4 |
|  1 |            1213 |           5 |
+----+-----------------+-------------+

我需要什么:

+----+-----------------+-------------+
| id | COUNT(votes.id) | question_id |
+----+-----------------+-------------+
|  1 |            1185 |           1 |
|  1 |            1170 |           2 |
|  1 |            1209 |           3 |
|  1 |            1230 |           4 |
|  1 |            1213 |           5 |
|  2 |            null |           1 |
|  2 |            50   |           2 |
|  2 |            333  |           3 |
|  2 |            1230 |           4 |
|  2 |            1213 |           5 |
|  3 |            null |           1 |
|  3 |            50   |           2 |
|  3 |            333  |           3 |
|  3 |            null |           4 |
|  3 |            5555 |           5 |
+----+-----------------+-------------+

2 个答案:

答案 0 :(得分:2)

group by条款缺少applications.id

SELECT applications.id, COUNT(votes.id), votes.question_id
FROM applications
LEFT OUTER JOIN votes ON votes.application_id = application.id
group by applications.id, votes.question_id

答案 1 :(得分:1)

您应该按applications.id以及questions.id

进行分组
SELECT a.id, COUNT(votes.id), votes.question_id
FROM applications a LEFT OUTER JOIN
     votes v
     ON v.application_id = a.id
GROUP BY a.id, v.question_id;

然而,这不会产生你想要的。您似乎想要申请的所有问题,无论是否有任何投票。如果是这样,这可能就是你想要的:

SELECT a.id, q.question_id, COUNT(v.application_id)
FROM applications a CROSS JOIN
     (SELECT DISTINCT question_id FROM votes) q LEFT JOIN
     votes v
     ON v.application_id = a.id and v.question_id = q.question_id
GROPU BY a.id, q.question_id;