【问题标题】:Find rows where sum of columns from multiple rows is greater than X查找多行中的列总和大于 X 的行
【发布时间】:2021-11-13 16:25:06
【问题描述】:

解释这个问题的最佳方法是通过它可以解决的现实生活示例。 我有两个表,匹配概览和匹配属性

比赛概览看起来像

id, home_id, away_id, date, result

虽然匹配属性看起来像

id, match_id, attribute_id, attribute_value

其中 match_id 是匹配概览表中 id 的外键,而属性 id 是类似属性的整数表示,

home_goals_full_time or total_yellow_cards or away_goals_extra_time

我想查询比赛属性以查找总进球数大于 X 的所有比赛。

由于每个属性都是自己的一行,我们需要找到所有属性 id 为 {3,4,5,6} 的行,如果 3 和 4 的总和 (home_goals_full_time + away_goals_full_time) 为大于 X 或 5 和 6 (home_goals_extra_time + away_goals_extra_time) 之和大于 X。

一种解决方案是在我的比赛概览表中添加一个总进球数列并搜索它,但是我希望能够为我的任何属性执行此操作,其中有很多属性,并且不是每场比赛都有一个属性,如果我为每个属性在匹配概览表中添加一列,该表将非常宽且充满空值。

是否可以在我输入值 X 的地方进行查询,并返回所有属性总和大于(或小于)我的 X 的游戏?或者这是否需要多次查询或可能需要重新设计我的架构。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    此任务的另一个直接查询:

    select * 
    from match_overview m
    where 
    (
      select sum(ma.attribute_value)
      from match_attributes ma
      where ma.match_id = m.id
      and ma.attribute_id in (3, 4)
    ) > @X
    or
    (
      select sum(ma.attribute_value)
      from match_attributes ma
      where ma.match_id = m.id
      and ma.attribute_id in (5,6)
    ) > @X;
    

    还有一个:

    select * 
    from match_overview m
    where id in
    (
      select match_id
      from match_attributes
      where attribute_id in (3, 4)
      group by match_id
      having sum(attribute_value) > @X
    ) 
    or id in
    (
      select match_id
      from match_attributes
      where attribute_id in (5, 6)
      group by match_id
      having sum(attribute_value) > @X
    );
    

    【讨论】:

      【解决方案2】:

      这很简单:

      select m.id
      from match_overview m
      join match_attributes ma on ma.match_id=m.id and ma.attribute_id in (3,4,5,6)
      group by m.id
      having sum(case when ma.attribute_id in (3,4) then ma.attribute_value end) > X
          or sum(case when ma.attribute_id in (5,6) then ma.attribute_value end) > X
      

      【讨论】:

        猜你喜欢
        • 2019-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-18
        相关资源
        最近更新 更多