[英]Check multiple values in a select statement
給定一個具有這樣的銷售額的表:
| 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,但我不知道如何從那里繼續。
這會選擇不存在某個制造商尚未購買的產品的所有用戶-因此,他們已經購買了該制造商的所有產品。
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
我會這樣寫查詢:
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
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.