首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

优化union解决办法

2012-01-18 
优化union表名:table1表结构:idparentidchildid11122211333441145511我现在用的sql语句是:(selectchildida

优化union
表名:table1
表结构:
id           parentid       childid
1               11                   22
2               11                   33
3               44                   11  
4               55                   11          

我现在用的sql语句是:
(select   childid   as   A   from   table1   where   parentid= '11 ')   union   (select   parentid   as   A   from   table1   where   childid= '11 '.)

得到的结果是:
    A
    22
    33
    44  
    55

我想问一下,有没有更简单、效率更高的的sql能实现这个功能。

[解决办法]
select
(case when parentid=11 then childid else parentid end) as A
from
table1
where
parentid=11 or childid=11
[解决办法]
id parentid childid
1 11 22
2 11 33
3 44 11
4 55 11


declare @a table(id int identity(1,1),parentid int,childid int)
insert @a
select 11,22
union all
select 11,33
union all
select 44,11
union all
select 55,11
--------------------------
select case when parentid=11 then childid else parentid end a
from @a


得到的结果是:
A
22
33
44
55

热点排行