【发布时间】:2020-07-22 08:57:37
【问题描述】:
我有 3 个表,Action、ActionType 和 Member。我正在尝试打印一个表格,显示特定成员的特定状态(表格动作的属性)中各种 ActionType 的数量;基本上为每个 ActionType 获取一行,为每个状态获取一列(Analysed (boolean)、Todo (boolean)、Done (boolean))。 假设我们有 3 种动作类型,查询应该返回一个 3x3 的网格。
现在我可以通过做类似的事情轻松完成一半
select t.name,
coalesce(sum(a.Analyzed), 0) as 'Analyzed',
coalesce(sum(a.Todo), 0) as 'Todo',
coalesce(sum(a.Done), 0) as 'Done'
from Action a
right join ActionType t on t.id = a.id_type_action
group by t.id
这很好用。当我尝试使用 join 或 where 条件在 Member 表上添加条件时,就会出现问题。我似乎找不到诀窍,要么条件没有过滤我的动作/动作类型的总和,要么它确实过滤了它们,但只打印了至少有一个单元格的行' t 0 - 虽然无论如何我都想要一个 3x3 网格,即使它充满了 0。
样本数据:
ActionType : id, name
insert into ActionType(10, 'Type1')
insert into ActionType(20, 'Type1')
insert into ActionType(30, 'Type1')
Member : id, name
insert into Member(100, 'Alice')
insert into Member(200, 'Bob')
Action : id, action_type_id, member_id, analyzed, todo, done
insert into Action(1, 10, 100, 1, 0, 0);
insert into Action(2, 10, 100, 1, 0, 0);
insert into Action(3, 10, 200, 0, 1, 0);
所需的输出*当在 Bob* 上过滤时(类似于 'where member.name = 'Bob'):
ActionType Analysed Todo Done
Type1 0 1 0
Type2 0 0 0
Type3 0 0 0
在 Alice 上过滤时所需的输出(类似于 'where member.name = 'Alice'):
ActionType Analysed Todo Done
Type1 2 0 0
Type2 0 0 0
Type3 0 0 0
【问题讨论】:
标签: mysql join where-clause