【问题标题】:Postgresql Return multiple rows, if one row satisfies a conditionPostgresql 返回多行,如果一行满足条件
【发布时间】:2014-11-25 10:08:49
【问题描述】:

我有下表:

表名:耶

id | tagname |  value  
----+---------+---------
0  | Farbe   | Gelb
0  | Preis   | 1.15
0  | Thema   | Herbst
1  | Farbe   | Maigrün
1  | Preis   | 1.15
1  | Thema   | Herbst
2  | Farbe   | Schwarz
2  | Preis   | 1.15
2  | Thema   | Sommer

我想要的是获取一个 id 的所有行,其中一个或多个条件满足,一个或多个不满足。 例如,如果我希望所有id 及其行在表中tagname='Preis'、value='1.15' 和tagname=Thema、value='Herbst' 满足,但不希望id 其中tagname='Farbe'、@ 987654329@ 变为真。结果应如下所示:

id | tagname |  value  
----+---------+---------
0  | Farbe   | Gelb
0  | Preis   | 1.15
0  | Thema   | Herbst
1  | Farbe   | Maigrün
1  | Preis   | 1.15
1  | Thema   | Herbst

当满足至少一个包含条件时,包含满足条件的id 的所有行都将出现在结果中。 但如果至少满足一个排除条件,则结果中不会出现对应的id行。

【问题讨论】:

    标签: sql postgresql filter


    【解决方案1】:

    如果你只想要ids,你可以这样做:

    select id
    from yay
    group by id
    having sum(case when tagname = 'preis' and value = '1.15' then 1 else 0 end) > 0 and
           sum(case when tagname = 'Thema' and value = 'Herbst' then 1 else 0 end) > 0 and
           sum(case when tagname = 'Farbe' and value = 'Schwarz' then 1 else 0 end) = 0;
    

    每个条件都会计算匹配行的数量。由于> 0,前两个至少需要一个匹配项(每个匹配项)才能匹配id。第三个说没有匹配,因为= 0。

    你可以通过加入回来获得原始数据:

    select yay.*
    from yay join
         (select id
          from yay
          group by id
          having sum(case when tagname = 'preis' and value = '1.15' then 1 else 0 end) > 0 and
                 sum(case when tagname = 'Thema' and value = 'Herbst' then 1 else 0 end) > 0 and
                 sum(case when tagname = 'Farbe' and value = 'Schwarz' then 1 else 0 end) = 0
         ) yid
         on yay.id = yid.id;
    

    【讨论】:

    • 这就是我一直在寻找的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2015-02-28
    • 2015-01-25
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多