0

我是 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子句以获取所有产品的结果时,我得到所有已扫描价格的商店(正确),但右连接的无价格侧仅显示尚未扫描任何价格的商店任何产品。(这是一个简单的星型模式,带有价格事实和产品、时间和商店的维度)。我将非常感谢帮助——我已经尝试了所有我能想到的方法,包括“在”、“不存在”和带有光标的存储过程,但我似乎每次尝试都碰壁了。

编辑澄清:

这是我想要实现的目标:

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
4

1 回答 1

0

我更喜欢使用 a 的可读性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

SQL 小提琴演示

于 2013-03-30T01:01:28.163 回答