微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PGSQL - 在 WHERE 子句中结合许多 AND + OR

如何解决PGSQL - 在 WHERE 子句中结合许多 AND + OR

我有这个表格格式:

| productid | price          |
| ----------| -------------- |
| 1         | 10             |
| 2         | 20             |
| 3         | 30             |
| 4         | 40             |

假设我想选择以下所有行: (productid 为 1 且价格超过 50)或 (productid 为 2 且价格超过 100)或 (productid 为 3,price 超过 20)

是否有更好的通用方法来实现它(类似于带有索引的数组或其他东西),例如:

select * from table where (productid = 1 and price > 50) OR
                          (productid = 2 and price > 100) OR
                          (productid = 3 and price > 20)

解决方法

我会使用 values 子句:

select * 
from the_table t
  join ( 
     values (1,50),(2,100),(3,20)
  ) as p(productid,price) 
    on t.productid = p.productid 
   and t.price > p.price;
,
with conditions as (
select a[1]::int as product_id,a[2]::int as min_price
from (select regexp_split_to_array(unnest(string_to_array('1,50;2,100;3,20',';')),',')) as dt(a)
)
select t.* from my_table t
  inner join conditions c on t.product = c.product_id
    and t.price >= c.min_price

测试数据:

drop table if exists my_table;
create temp table if not exists my_table(product int,price int,note text);
insert into my_table
select 1,10,'some info 1:10' union all
select 1,20,'some info 1:20' union all
select 1,50,'some info 1:50' union all
select 2,'some info 2:10' union all
select 2,100,'some info 2:100:1' union all
select 2,'some info 2:100:2' union all
select 3,30,'some info 3:30' union all
select 4,40,'some info 4:40';

结果:

1   50  "some info 1:50"
2   100 "some info 2:100:1"
2   100 "some info 2:100:2"
3   30  "some info 3:30"


unnest(string_to_array('1,';'))-- split CSV to rows
regexp_split_to_array(....,') -- split CSV to columns

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。