2013-03-30 258 views
1

我是mySQL的新手,我正在努力编写一个查询,该查询将列出扫描产品价格的所有商店以及尚未扫描产品的商店。下面给出正确的结果的单品: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 

回答

0

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

+0

感谢您的答复(也喜欢您的格式 - 更容易阅读!) - 你的查询给出了相同的结果;我只收到没有任何产品扫描价格的商店...我需要那些尚未针对每种产品进行扫描的商店。 – zimboy

+0

@ user2226020 - 以上应该会为您发布已发布= 1和chainId = 5的所有商店。左连接将返回所有商店,并且仅匹配其他表中的记录。不完全确定您的意思是“没有针对每种产品进行扫描的商店”。 – sgeddes

+0

我编辑了原创,试图澄清我试图达到的目标。 – zimboy