mssql - 如果第一个表没有结果,则从另一个表中选择

时间:2013-09-19 09:49:40

标签: sql-server

我必须运行查询才能找到价格。我有多个价格表,每个都在自己的表中。 customer_price,default_price和minimum_price。

并非所有价格表都包含所有产品,有时产品可能不会出现在任何价格表中,然后价格需要返回0才能显示价格。

所以我想:

select price from customer_price where customer='walmart' and product='whitebread'

如果这返回结果那么一切都很好。如果结果为0,则NULL或查询不返回我想要运行的行:

select price from default_price where customer='walmart' and product='whitebread'

如果这返回结果那么一切都很好。如果结果为0,则NULL或查询不返回任何我想简单返回0的行。

我不知道该怎么办。我尝试了一个case语句,但如果在结果中找不到行,case语句将失败。我该怎么做或说if 0 results then

提前感谢,一如既往。

3 个答案:

答案 0 :(得分:2)

select top 1 price from (
    select 1 as qorder, price from customer_price where price > 0 and customer='walmart' and product='whitebread'
    union
    select 2 as qorder, price from default_price where price > 0 and customer='walmart' and product='whitebread'
    union 
    select 3 as qorder, 0 
    ) as sq
order by qOrder

答案 1 :(得分:2)

case when
(select count(price) from customer_price where customer='walmart' and product='whitebread' and price is not null and price > 0) > 0 
then 
    select price from customer_price where customer='walmart' and product='whitebread'
else 
    select price from default_price where customer='walmart' and product='whitebread'   
end 

答案 2 :(得分:0)

我正在编写一个双向解决方案,其中包括清空选择查询您可以替换您的查询

... {
  left: auto;
  right: 12px;
}