1

Is there a better way to perform the following query? I'm trying to see if a user has all of the products in a certain category

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
4

2 回答 2

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
于 2012-09-19T15:21:00.120 回答
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
   )

应该比迄今为止提出的任何一种解决方案都要快。(只要我对矛盾问题的解释合适。)

于 2012-09-19T19:12:06.283 回答