如何在Postgresql中结合mulltiple IN子句?

时间:2016-09-29 07:58:06

标签: postgresql relational-division

我有两张桌子: 列ID和标题的商品 过滤列id 还有一个交叉连接表:filter_good,包含列filterid和goodid 我需要在一个过滤器ID列表中找到与任何过滤器匹配的商品,并且还匹配另一个过滤器ID列表中的任何过滤器。 我试图使用这个查询来实现它而没有运气:

SELECT
    goods.*
FROM
    goods
JOIN filter_good ON goods.id = filter_good.goodid
WHERE filter_good.filterid IN (3)
AND filter_good.filterid IN (1, 2)

如何做到这一点?

我需要返回仅在存在ID为3且ID为1或2

的记录时才匹配的记录

2 个答案:

答案 0 :(得分:2)

嗯,你的问题真的不是那么清楚,但你可能需要一个EXISTS条款:

SELECT
    *
FROM
    goods
WHERE 
  EXISTS (
    SELECT * 
    FROM filter_good 
    WHERE goods.id = filter_good.goodid
      AND filter_good.filterid IN (3)
  )
  AND EXISTS (
    SELECT * 
    FROM filter_good 
    WHERE goods.id = filter_good.goodid
      AND filter_good.filterid IN (1,2)
  )

答案 1 :(得分:0)

select g.id
from
    goods g
    inner join
    filter_good fg on g.id = fg.goodid
group by g.id
having bool_or(fg.filter_id = 3) and bool_or(fg.filter_id in (1,2))

表别名使其更清晰。

检查bool_or aggregate function

如果需要其他goods列,请将其包装在外部查询中:

select *
from goods
where id in (
    select g.id
    from
        goods g
        inner join
        filter_good fg on g.id = fg.goodid
    group by g.id
    having bool_or(fg.filter_id = 3) and bool_or(fg.filter_id in (1,2))
)