Sql 在不同的表格中检查不同的价格
假设我有3张桌子:Sql 在不同的表格中检查不同的价格,sql,sql-server,Sql,Sql Server,假设我有3张桌子: 项目表(关于项目的所有信息) 项目定价(同一项目的多个价格) 特价(如果我们对某些项目或促销有特价) 我想建立一个查询来检查价格是否存在于特殊价格表中,如果没有,则显示它,如果没有,则取项目定价表中的内容。换句话说,我想先用price if not检查项目是否存在于特殊价格表中,然后检查项目定价表。 这是我尝试过的,当然没有给出正确的答案 select T0.itemcode,T0.ItemName,T0.OnHand,T1.price, T2.Price as Specia
这是我尝试过的,当然没有给出正确的答案
select T0.itemcode,T0.ItemName,T0.OnHand,T1.price, T2.Price as Special
from ITEM T0, PRICES T1, S_PRICES T2
where
T0.ItemCode=T1.ItemCode
and T0.ItemCode=T2.ItemCode
看起来很简单,但我不知道怎么做??我正在使用SQLServer2008R2
任何帮助都将不胜感激
谢谢。简单规则:只需对来自子句的
中的逗号说“不”。现在是学习显式join
语法而不是where
子句中条件所在的隐式语法的时候了
select i.itemcode, i.ItemName, i.OnHand, p.price, sp.Price as Special,
coalesce(sp.Price, p.price) as ThePriceIWant
from ITEM i left outer join
PRICES p
on p.itemCode = i.ItemCode left outer join
S_PRICES sp
on sp.itemCode = i.ItemCode;
如果您使用显式联接编写查询,那么答案将是“您需要使用左外部联接”。你猜怎么着?当条件位于where
子句中时,这是不容易做到的
select i.itemcode, i.ItemName, i.OnHand, p.price, sp.Price as Special,
coalesce(sp.Price, p.price) as ThePriceIWant
from ITEM i left outer join
PRICES p
on p.itemCode = i.ItemCode left outer join
S_PRICES sp
on sp.itemCode = i.ItemCode;
请注意使用coalesce()
获取所需价格的逻辑。使用表缩写作为表别名——它们使查询更容易理解。简单规则:只需对来自
子句的中的逗号说“不”。现在是学习显式join
语法而不是where
子句中条件所在的隐式语法的时候了
select i.itemcode, i.ItemName, i.OnHand, p.price, sp.Price as Special,
coalesce(sp.Price, p.price) as ThePriceIWant
from ITEM i left outer join
PRICES p
on p.itemCode = i.ItemCode left outer join
S_PRICES sp
on sp.itemCode = i.ItemCode;
如果您使用显式联接编写查询,那么答案将是“您需要使用左外部联接”。你猜怎么着?当条件位于where
子句中时,这是不容易做到的
select i.itemcode, i.ItemName, i.OnHand, p.price, sp.Price as Special,
coalesce(sp.Price, p.price) as ThePriceIWant
from ITEM i left outer join
PRICES p
on p.itemCode = i.ItemCode left outer join
S_PRICES sp
on sp.itemCode = i.ItemCode;
请注意使用coalesce()
获取所需价格的逻辑。并且使用表缩写作为表别名——它们使查询更容易理解。大致如下
select T0.itemcode,T0.ItemName,T0.OnHand,
IsNull(T2.Price, T1.Price) As Price
from ITEM as T0
left join PRICES as T1
on T1.ItemCode = T0.ItemCode
left join S_PRICES as T2
on T2.ItemCode = T0.ItemCode
这假设有零或一个特殊价格和零或一个价格
select T0.itemcode,T0.ItemName,T0.OnHand,
IsNull(T2.Price, T1.Price) As Price
from ITEM as T0
left join PRICES as T1
on T1.ItemCode = T0.ItemCode
left join S_PRICES as T2
on T2.ItemCode = T0.ItemCode
这假设有零或一个特殊价格和零或一个价格