【问题标题】:Issue with joins & where clause连接和 where 子句的问题
【发布时间】: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


    【解决方案1】:

    我首先将right join 重写为left join(我觉得这更容易理解)。然后,您可以在过滤给定的name 时添加另一个连接以带来member 表:

    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 actiontype t
    inner join member m on m.name = 'Bob'
    left join action a on a.id_type_action = t.id and a.member_id = m.id
    group by t.id, t.name
    

    【讨论】:

    • 我已经尝试过了,但它似乎并没有只过滤 Bob 操作的总和。第一行的输出是 (Type1, 2, 1, 0) 而不是 (Type1, 0, 1, 0) 。
    • @ChristopheSchutz:我稍微改变了连接逻辑。请再试一次。
    • 现在它可以正确过滤,但出现了我已经遇到的第二个问题:我只在输出中获取不只包含 0 的行,这是我不想要的。 (输出不包括 Type2 和 Type3 的行,因为内部连接找不到它们的匹配项)。
    猜你喜欢
    • 2016-04-23
    • 2022-09-24
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多