如何用PostgREST实现PostgreSQL多列组合IN条件查询?
PostgREST实现多字段组合IN查询的方法
问题场景
现有PostgreSQL表test_1,结构及数据如下:
| ID | container_id | product_id |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 2 | 2 |
需要执行的目标SQL查询为:
select * from test_1 where (container_id,product_id) in ((1,1),(1,2),(2,1));
该查询应返回ID为1至3的行。
当前构造的PostgREST请求URL为:
http://localhost:8080/test_1?&product_id=in.(1,2)&container_id=in.(1,2)
但此URL会返回所有4行,不符合需求——因为它对应的SQL是where container_id in (1,2) AND product_id in (1,2),是两个字段各自独立的IN条件,而非字段组合的匹配逻辑。
解决方案
PostgREST支持多字段组合的IN查询,需要使用行构造器配合in操作符,正确的请求URL格式如下:
http://localhost:8080/test_1?and=(container_id,product_id).in.((1,1),(1,2),(2,1))
这个URL对应的SQL逻辑完全匹配目标查询,会精准返回ID为1、2、3的行,满足需求。
内容的提问来源于stack exchange,提问作者renaise21
相关产品推荐
相关产品推荐

