PSQL按顺序选择a或b,但如果a和b同时存在,则不能同时选择a和b

时间:2019-05-29 06:05:18

标签: sql database postgresql psql logical-operators

我有一个PSQL表

+--------+------+------+------+
|  Col1  | Col2 | Col3 | Col4 |
+--------+------+------+------+
|    001 | 00A  | 00B  | 001  |
| 001001 | 00A  | 00B  | 001  |
|    002 | 00X  | 00Y  | 002  |
| 002002 | 00X  | 00Y  | 002  |
+--------+------+------+------+

我有以下PSQL查询:

select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
order by Col3 asc; 

我得到前两行。

这里发生的是,它与OR条件的两个条件都匹配。我只需要匹配 or条件之一。也就是说,如果第一个条件(Col1='001001')为true,则不评估下一个条件。 我只需要选择第二行(| 001001 | 00A | 00B | 001 |

我已经使用EXCEPT

建立了另一个查询
select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
    except (select *
            from my_table
            where Col1 != '001'
              and Col2 = '00A')
order by Col3 asc
limit 1;

我想知道这个工作是否还有其他优雅的查询?

2 个答案:

答案 0 :(得分:0)

这能给您想要的东西吗?

select *
from my_table
where (Col1 = '001' and Col2 != '00A')
    or ((Col1 is null or Col1 = '') and Col4 = '001' and Col2 = '00A')
order by Col3 asc;

答案 1 :(得分:0)

您在一个地方说col1 = '001001'并在查询中使用001时,您的解释会令人困惑。但是我想您想使用比较层次结构,并返回每个组中最高的层次结构(col2,col3,col4)。使用DISTINCT ON。更改条件以任意方式返回适当的行。

SELECT DISTINCT ON (col2, col3, col4) * 
  FROM     my_table WHERE  col2 = '00A' 
ORDER  BY col2, 
          col3, 
          col4, 
          CASE 
            WHEN col1 = '001001' THEN 1 
            WHEN col4 = '001'    THEN 2 
          END; 

DEMO

相关问题