【发布时间】:2021-01-06 13:20:03
【问题描述】:
假设我有两个表 - 游戏和动作 - 我想要第三个表中所示的输出。
games
+----+---------+
| id | title |
+----+---------+
| 1 | "one" |
| 2 | "two" |
| 3 | "three" |
+----+---------+
actions
+----+---------+------+---------+
| id | game_id | type | user_id |
+----+---------+------+---------+
| 1 | 1 | 1 | 2 |
| 2 | 2 | 1 | 2 |
| 3 | 3 | 1 | 2 |
| 4 | 1 | 2 | 1 |
| 5 | 1 | 2 | 2 |
| 6 | 1 | 2 | 3 |
| 7 | 1 | 3 | 1 |
| 8 | 1 | 3 | 1 |
| 9 | 1 | 3 | 3 |
| 10 | 2 | 3 | 1 |
| 11 | 2 | 3 | 1 |
+----+---------+------+---------+
expected output for game_aggregates
+----+---------+------------------+--------------------+
| id | title | n_actions_type_3 | n_actions_type_all |
+----+---------+------------------+--------------------+
| 1 | "one" | 3 | 7 |
| 2 | "two" | 2 | 3 |
| 3 | "three" | 0 | 1 |
+----+---------+------------------+--------------------+
我可以从一个简单的开始
select
g.*,
count(a3.id) as n_actions_type_3
from games g
left join actions a3
on g.id = a3.game_id and a3.type = 3
group by g.id;
我会得到的。
+----+---------+------------------+
| id | title | n_actions_type_3 |
+----+---------+------------------+
| 1 | "one" | 3 |
| 2 | "two" | 2 |
| 3 | "three" | 0 |
+----+---------+------------------+
到目前为止,一切都很好。
现在,如果我添加多个 LEFT JOINS - 它不起作用 - 数字非常不同:
-- doesn't result in correct counts
select
g.*,
count(a3.id) as n_actions_type_3,
count(a_all.id) as n_actions_type_all,
from games g
left join actions a3
on g.id = a3.game_id and a3.type = 3
left join actions a_all
on g.id = a_all.game_id
group by g.id;
一种方法是将 n_actions_type_3 上的较早结果包装在 select 语句中,然后为 n_actions_type_all 执行左连接 - 但一次只会执行一次左连接。
是否可以使用多个左连接获得所需的输出?
【问题讨论】:
-
请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入作为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出尽可能少的代码,即您显示的代码可以通过您显示的代码扩展为不正常的代码。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)和输入为格式化为表的代码的 SQL。 How to Ask 暂停总体目标的工作,将代码砍到第一个表达式,没有给出你期望的内容,说出你期望的内容和原因。
-
这涉及一个常见错误,人们想要一些连接,每个可能涉及不同的键,一些子查询,每个可能涉及连接和/或聚合,但他们错误地尝试完成所有连接然后全部聚合或聚合以前的聚合。在适当的行上编写单独的聚合和/或聚合一个案例语句选择行;加入一个独特的列集。有时 DISTINCT 聚合在非键连接后选择正确的值。 sum data from multiple tables