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
感谢您的答复(也喜欢您的格式 - 更容易阅读!) - 你的查询给出了相同的结果;我只收到没有任何产品扫描价格的商店...我需要那些尚未针对每种产品进行扫描的商店。 – zimboy
@ user2226020 - 以上应该会为您发布已发布= 1和chainId = 5的所有商店。左连接将返回所有商店,并且仅匹配其他表中的记录。不完全确定您的意思是“没有针对每种产品进行扫描的商店”。 – sgeddes
我编辑了原创,试图澄清我试图达到的目标。 – zimboy