1

我需要简单地遵循 SQL 查询。有什么办法可以得到吗??

select * 
  from product a 
  where a.brand_id 
    in (select ib.brand_id from 
      SUBSCRIBED_CHANNEL ia inner join product ib 
      where ia.product_id=ib.product_id and ia.user_id=3)
    and a.product_id not in (select ib.product_id from SUBSCRIBED_CHANNEL ia 
    inner join product ib where ia.product_id=ib.product_id and ia.user_id=3)

编辑:四个表:

product (PRODUCT_NAME, PRODUCT_ID, BRAND_ID)
SUBSCRIBED_CHANNEL (USER_ID, PRODUCT_ID)
brand (BRAND_NAME, BRAND_ID)
user (..., user_id)

product to brand -> many to one
product to user -> many to many
subscribed_channel -> 中间表


I需要获取用户未订阅的产品。
例如:如果耐克品牌有产品 xx、yy 和 zz
,如果用户只订阅了 xx,那么我的查询结果必须只给出 yy、zz。

4

1 回答 1

0

(修改)尝试:

select distinct a.* 
from product a
join product b on a.brand_id = b.brand_id 
join subscribed_channel i on b.product_id = i.product_id and i.user_id=3
left join subscribed_channel n on a.product_id = n.product_id and n.user_id=3
where n.product_id is null

或者:

select a.* 
from product a
join product b on a.brand_id = b.brand_id 
join subscribed_channel i on b.product_id = i.product_id and i.user_id=3
group by a.product_id
having sum(case when a.product_id = b.product_id then 1 else 0 end) = 0
于 2013-05-26T15:35:22.403 回答