SQL 仅选择在每个地点均有售的产品
SQL Selecting ONLY products that are available in every location
我正在尝试将这些查询与 select 产品的子查询结合起来,这些产品存在于 store_location table 的每个位置。此架构中有多个 table,但最相关的是 Product、Sells、Sizes 和 Store_Location。 Sells 是包含 product_id 和 store_location_id 的 table。因此可以将销售加入 store_location(在子查询中?)
我已经学会了如何进行聚合,似乎我需要计算位置的数量,但我如何使用 where 子句中的比较来过滤掉并非随处可用的产品?希望您能看到有关架构的足够信息以及我尝试使用以下代码执行的操作:
编辑:感谢用关系划分标记这个的人,你可能已经给了我我需要的线索!
select distinct product_name, size_option
from product p
join available_in a on p.product_id = a.product_id
join sells s on p.product_id = s.product_id
join sizes si on si.sizes_id = a.sizes_id
order by size_option desc;
select product_id
from sells s
join store_location st on st.store_location_id = s.store_location_id
where ???
select count(store_location_id)
from store_location
所以我阅读了关系除法并得出了答案:
select distinct product_name, size_option
from product p
join available_in a on p.product_id = a.product_id
join sells s on p.product_id = s.product_id
join sizes si on si.sizes_id = a.sizes_id
join store_location st on st.store_location_id = s.store_location_id
where s.product_id in (select x.product_id
from sells x)
group by product_name, size_option
having count(*) = (select count(*) from store_location)
order by size_option desc;
有效!我很欣赏这个线索:)
我正在尝试将这些查询与 select 产品的子查询结合起来,这些产品存在于 store_location table 的每个位置。此架构中有多个 table,但最相关的是 Product、Sells、Sizes 和 Store_Location。 Sells 是包含 product_id 和 store_location_id 的 table。因此可以将销售加入 store_location(在子查询中?)
我已经学会了如何进行聚合,似乎我需要计算位置的数量,但我如何使用 where 子句中的比较来过滤掉并非随处可用的产品?希望您能看到有关架构的足够信息以及我尝试使用以下代码执行的操作:
编辑:感谢用关系划分标记这个的人,你可能已经给了我我需要的线索!
select distinct product_name, size_option
from product p
join available_in a on p.product_id = a.product_id
join sells s on p.product_id = s.product_id
join sizes si on si.sizes_id = a.sizes_id
order by size_option desc;
select product_id
from sells s
join store_location st on st.store_location_id = s.store_location_id
where ???
select count(store_location_id)
from store_location
所以我阅读了关系除法并得出了答案:
select distinct product_name, size_option
from product p
join available_in a on p.product_id = a.product_id
join sells s on p.product_id = s.product_id
join sizes si on si.sizes_id = a.sizes_id
join store_location st on st.store_location_id = s.store_location_id
where s.product_id in (select x.product_id
from sells x)
group by product_name, size_option
having count(*) = (select count(*) from store_location)
order by size_option desc;
有效!我很欣赏这个线索:)