如何在 Postgresql 中组合多个 IN 子句?
How to combine mulltiple IN clause in Postgresql?
我有两个 table:
带有列 ID 和标题的商品
使用列 ID 进行过滤
还有一个 cross-join table: 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)
如何做到这一点?
我需要 return 仅当存在 ID 为 3 且 ID 为 1 或 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)
)
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))
Table 别名更清晰。
如果需要其他 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))
)
我有两个 table: 带有列 ID 和标题的商品 使用列 ID 进行过滤 还有一个 cross-join table: 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)
如何做到这一点?
我需要 return 仅当存在 ID 为 3 且 ID 为 1 或 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)
)
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))
Table 别名更清晰。
如果需要其他 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))
)