给出一个像这样的销售表:
| 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,但我不知道如何从那里继续。
答案 0 :(得分: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
答案 1 :(得分: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
);