假设我们有一个标准,并且属于产品和类别之间的许多关联 product_categories表由product_id和category_id对组成。
我们有category_id列表,需要选择属于所有这些类别的所有产品。
我想到的最好的方法是在编程语言级别由 AND 连接的where子句中有多个 EXISTS():
SELECT * FROM products p WHERE
EXISTS(SELECT * FROM product_categories pc
WHERE pc.product_id = p.id AND pc.category_id = {first_id}) AND
EXISTS(SELECT * FROM product_categories pc
WHERE pc.product_id = p.id AND pc.category_id = {second_id}) AND ...
Postgres 8.4中EXISTS 速度很快,因此这种方法没有性能问题。
但是我更聪明地做这种类型的查询了吗?
答案 0 :(得分:1)
SELECT * FROM products p WHERE
EXISTS(SELECT * FROM product_categories pc
WHERE pc.product_id = p.id AND pc.category_id = {first_id})
INTERSECT
SELECT * FROM products p WHERE
EXISTS(SELECT * FROM product_categories pc
WHERE pc.product_id = p.id AND pc.category_id = {second_id})
INTERSECT
....