【问题标题】:PostgreSQL How to get the rows that has two or more columns that meets the same conditionPostgreSQL 如何获取具有两个或多个满足相同条件的列的行
【发布时间】:2021-02-11 10:26:22
【问题描述】:

我需要有两列或多列满足相同条件的行。 像这样的:

id | column1 | column2 | column3
--------------------------------
1  | 'yes'   | 'yes'   |  'yes'
2  | 'yes'   | 'yes'   |  'no'
3  | 'yes'   | 'no'    |  'no'
4  | 'no'    | 'no'    |  'no'
5  | 'yes'   | 'no'    |  'yes'
6  | 'no'    | 'yes'   |  'yes'

所以,我需要执行一个返回 id 为 1,2,5,6 的行的 SELECT 子句 逐一进行 AND/OR 组合会产生一个非常大的子句(实际上有 8 列)。 还有其他更快的方法吗?

谢谢

【问题讨论】:

    标签: sql postgresql count combinations where-clause


    【解决方案1】:

    这里有一个选项,它依赖于 Postgres 将条件理解为布尔值和整数的能力:

    select t.*
    from mytable t
    where (column1 = 'yes')::int 
        + (column2 = 'yes')::int 
        + (column3 = 'yes')::int >= 2
    

    您可能还想考虑横向连接:一开始输入的时间会更长,但更容易扩展。

    select t.*
    from mytable t
    cross join lateral ( 
        select count(*) cnt
        from (values (column1), (column2), (column3)) x(col)
        where x.col = 'true'
    ) x
    where x.cnt >= 2
    

    【讨论】:

    • 乍一看显然解决了我的问题!非常感谢。我整个下午都在寻找这样的东西,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多