Postgres,检查一个集合是否包含另一个集合

时间:2012-09-19 15:15:05

标签: postgresql dataset subquery

有没有更好的方法来执行以下查询?我正在尝试查看用户是否拥有特定类别的所有产品

SELECT t1.id 
  FROM 
    (SELECT count(product_id) as count, product_id FROM categories group by product_id) t1 
  INNER JOIN 
    (SELECT count(product_id) as count, product_id FROM categories INNER JOIN user_products on user_products.product_id = categories.product_id where user_id=116 group by product_id) t2 
  ON t1.id=t2.id 
  WHERE t1.count = t2.count

2 个答案:

答案 0 :(得分:1)

嗯,这应该有效,但这样更好吗?不确定......

select 
c.product_id
from categories c
left join user_products up on up.product_id = c.product_id and up.user_id = 116
group by c.product_id
having  sum (case when up.product_id is null then 0 else 1 end) = 0

答案 1 :(得分:1)

如果用户在“类别”中包含所有产品(或者根本不存在),则会返回TRUE

SELECT count(*) = 0
FROM   categories c
WHERE  NOT EXISTS (
   SELECT 1
   FROM   user_products u
   WHERE  u.product_id = c.product_id
   AND    u.user_id = 116
   )

应该比目前提供的任何解决方案都快。 (条件是我对矛盾问题的解释适合。)