我是mySQL的新手,我正在努力编写一个查询,列出所有已扫描产品价格的商店以及尚未扫描的商店。以下为单个产品提供了正确的结果:
select distinct(s.id) as store_id, s.chainID as chain_id, p1.productID as product_id,
s.chain, s.location, s.city, prd.brand, prd.product, prd.quantity, prd.size, prd.unit
from analytics.price p1 -- Fact table with prices
join analytics.pricetime pt -- Dimension table with time a price was scanned
on p1.priceTimeID = pt.id
join analytics.product prd -- Dimension table with products
on p1.productID = prd.id
and prd.published = 1
right join analytics.store s -- Dimension table with stores and the chain they belong to
on p1.storeID = s.id
and p1.chainID = s.chainID
and p1.productID = 46720
and p1.priceTimeID between 2252 and 2265
where s.published=1
and s.chainID = 5;
当我删除p1.productID = 46720条款以获得所有产品的结果时,我得到所有已扫描价格的商店(正确),但右边加入的无价格一侧仅显示未扫描任何价格的商店任何产品。 (这是一个简单的星型模式,具有价格事实和产品,时间和商店的尺寸)。我非常感谢帮助 - 我已经尝试过各种方式,包括“in”,“not exists”和光标存储过程,但我似乎每次尝试都会碰壁砖。
编辑澄清:
这是我想要实现的目标:
Price table
Product Chain Store Price
100 5 1 $10
101 5 2 $20
Store table
Chain Store
5 1
5 2
5 3
Desired Result
Product Chain Store Price
100 5 1 $10
100 5 2 NULL
100 5 3 NULL
101 5 1 NULL
101 5 2 $20
101 5 3 NULL
Actual Result
Product Chain Store Price
100 5 1 $10
101 5 2 $20
NULL 5 3 NULL
我更喜欢使用LEFT JOIN
的可读性 - 这应该返回chainid 5中所有已发布的商店和相关产品(给定标准)。
select distinct s.id as store_id, s.chainID as chain_id, s.chain, s.location, s.city,
prd.id as product_id, prd.brand, prd.product, prd.quantity, prd.size, prd.unit
from analytics.store s
left join analytics.price p1
on p1.storeID = s.id
and p1.chainID = s.chainID
and p1.priceTimeID between 2252 and 2265
left join analytics.product prd
on p1.productID = prd.id
and prd.published = 1
left join analytics.pricetime pt
on p1.priceTimeID = pt.id
where s.published=1
and s.chainID=5;
编辑 - 发表评论,看起来你正在寻找笛卡尔积:
SELECT P.Product, P.Chain, S.Store, IF(P.Store=S.Store,P.Price,NULL) Price
FROM Price P, Store S
WHERE P.Chain = 5
AND S.Chain = P.Chain
ORDER BY P.Product, S.Store