计算多次连接的表中的值
我在计算多次连接的表时遇到问题。
问题
表:
+----+----------+
| id | question |
+----+----------+
| 1 | Foo? |
+----+----------+
答案
表:
+----+-------------+--------+
| id | question_id | choice |
+----+-------------+--------+
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 1 | 1 |
| 4 | 1 | 2 |
| 5 | 1 | 3 |
| 6 | 1 | 3 |
+----+-------------+--------+
预期结果:(
+----------+-------+-------+-------+
| question | num_1 | num_2 | num_3 |
+----------+-------+-------+-------+
| Foo? | 3 | 1 | 2 |
+----------+-------+-------+-------+
失败的)查询及其结果:
SELECT
q.question AS question,
COUNT(a1.id) AS num_1,
COUNT(a2.id) AS num_2,
COUNT(a3.id) AS num_3
FROM
question q
LEFT JOIN answer a1 ON a1.question_id = q.id AND a1.choice = 1
LEFT JOIN answer a2 ON a2.question_id = q.id AND a2.choice = 2
LEFT JOIN answer a3 ON a3.question_id = q.id AND a3.choice = 3
GROUP BY
q.id
+----------+-------+-------+-------+
| question | num_1 | num_2 | num_3 |
+----------+-------+-------+-------+
| Foo? | 6 | 6 | 6 |
+----------+-------+-------+-------+
我不明白为什么会得到这个结果。 你能帮助我吗?
I have a problem counting a table joined several times.
The question
table :
+----+----------+
| id | question |
+----+----------+
| 1 | Foo? |
+----+----------+
The answer
one :
+----+-------------+--------+
| id | question_id | choice |
+----+-------------+--------+
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 1 | 1 |
| 4 | 1 | 2 |
| 5 | 1 | 3 |
| 6 | 1 | 3 |
+----+-------------+--------+
The expected result :
+----------+-------+-------+-------+
| question | num_1 | num_2 | num_3 |
+----------+-------+-------+-------+
| Foo? | 3 | 1 | 2 |
+----------+-------+-------+-------+
The (failing) query and its result :
SELECT
q.question AS question,
COUNT(a1.id) AS num_1,
COUNT(a2.id) AS num_2,
COUNT(a3.id) AS num_3
FROM
question q
LEFT JOIN answer a1 ON a1.question_id = q.id AND a1.choice = 1
LEFT JOIN answer a2 ON a2.question_id = q.id AND a2.choice = 2
LEFT JOIN answer a3 ON a3.question_id = q.id AND a3.choice = 3
GROUP BY
q.id
+----------+-------+-------+-------+
| question | num_1 | num_2 | num_3 |
+----------+-------+-------+-------+
| Foo? | 6 | 6 | 6 |
+----------+-------+-------+-------+
I don't understand why I get this result.
Can you help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为
choice = 1
给出 3 行,choice = 2
给出 1 行,choice = 3
给出 2 行,1 * 2 * 3 = 6。如果您删除
group by
并聚合并查看结果,那么结果应该很清楚。您可以使用Because
choice = 1
gives 3 rows,choice = 2
gives 1 row,choice = 3
gives 2 rows and1 * 2 * 3 = 6
. if you remove thegroup by
and aggregates and look at the results it should be clear. You can use如果您在没有计数和分组的情况下运行查询,您将看到得到如下结果:
正如预期的那样,有 6 行,因此每个别名字段将为您提供 6 的计数。Martin Smith 在上面得到了正确的答案。
If you run your query without the counts and grouping, you'll see you get results like this:
As expected, 6 rows, so each aliased field will give you a count of 6. Martin Smith's got the right answer above.