2015-05-09 40 views
1

我看起来像是一样的问题Union Select Only One Row 但是几乎没有什么不同。我的四个选择结合工会声明。它在sql中的速度有多快,如果我只选择第一行有四个选择

select top 1 value from (
    select 1 as id, value from resource where rkey = 'a' 
    union 
    select 2 as id, value from resource where rkey = 'b' 
    union 
    select 3 as id, value from resource where rkey = 'c' 
    union 
    select 4 as id, value from resource where rkey = 'd' 
) as x 
order by id 

每个select语句只给出一行或零行。我已经会使用所有选择的第一个结果。所以如果第一个select返回一行,那么其他选择应该被忽略。如果第二个选择返回行(第一个选择不返回行),则应忽略其他行。 etc ...

我的问题是:这种组合有多快,还是有更快的解决方案?

+2

UNION ALL通常比UNION快。 – jarlh

+1

这是无法回答的:它取决于数据库,表结构的实际数据,存储方式,索引等。 –

回答

0

如果key被索引的方式(但使用UNION ALL)可能是最好的。

否则尝试:

select top 1 value 
from resource 
where rkey in ('a', 'b', 'c', 'd') 
order by 
    case rkey 
    when 'a' then 1 
    when 'b' then 2 
    when 'c' then 3 
    when 'd' then 4 
    end 
1

或者跳过UNION

select top 1 value 
from resource 
where rkey in ('a','b','c','d') 
order by rkey