2015-04-12 61 views
0

給定一個表,銷售這樣的:檢查多個值

| PRODUCT_ID | USER_ID | 
|------------|---------| 
|   1 |  1 | 
|   2 |  1 | 
|   3 |  1 | 
|   3 |  2 | 
|   4 |  2 | 
|   1 |  3 | 
|   3 |  3 | 

而且隨着產品和製造商的表是這樣的:

| PRODUCT_ID | MANUFACTURER_ID | 
|------------|-----------------| 
|   1 |    1 | 
|   2 |    1 | 
|   3 |    2 | 
|   4 |    2 | 

我怎樣才能找到具有用戶買了製造商的所有產品?我知道我可以使用

SELECT * 
FROM product 
WHERE MANUFACTURER_ID = x 

找到哪些產品屬於製造商x,但我不知道如何從那裏繼續。

回答

1

所有用戶我會寫這樣的查詢:

select s.user_id 
from sales s join 
    products p 
    on s.product_id = p.product_id 
where p.manufacturer_id = x 
group by s.user_id 
having count(distinct s.product_id) = (select count(*) 
             from products 
             where manufacturer_id = x 
            ); 
1

這樣可以選擇所有沒有購買某個製造商的產品的用戶,因此他們購買了該製造商的所有產品。

select t1.user_id from (
    select user_id from sales s 
    join manufacturers m on s.product_id = m.product_id 
    where manufacturer_id = x 
    group by user_id 
) t1 where not exists (
    select 1 from manufacturers m 
    left join sales s on s.product_id = m.product_id and s.user_id = t1.user_id 
    where m.manufacturer_id = t1.manufacturer_id  
    and s.product_id is null  
) 

編輯

另一種方式是選擇已購買的所有產品

select t1.user_id from (
    select s.user_id, count(*) cnt from product p 
    join sales s on s.product_id = p.product_id 
    where p.manufacturer_id = x 
    group by s.user_id 
) t1 join (
    select count(*) cnt from product 
    where manufacturer_id = x 
) t2 on t2.cnt = t1.cnt