卡号1         卡号2       层数
11992354 11737870 2
12071238 11737884 2
11992261 11746354 2
11991892 11746421 2
11992778 11746736 2
11991906 11746747 2
11991947 11746839 2
12071230 11758017 2
12071416 11758017 2
11993048 11758327 2
11993049 11758327 2
12015766 11758849 2
11992394 11759005 2
11992983 11759042 2
11992291 11759668 2
11992292 11759668 2
12071284 11759856 2
12069922 12071284 3
现在我SELECT中WHERE的条件是“卡号2='11759856',怎么样可以得到如下记录
卡号1         卡号2       层数
12071284 11759856 2
12069922 12071284 3
我现在用如下方法实现:有没有效率更高的办法,谢谢!
select a.* from(
select 卡号1,卡号2,level as 层次,操作员,操作日期 from T_客户层次结构表 a,@t_level b 
where a.卡号1=b.id and 卡号2 is not null)a
inner join
(select 卡号1,卡号2,level as 层次,操作员,操作日期 from T_客户层次结构表 a,@t_level b 
where a.卡号1=b.id and 卡号2 is not null and 卡号2号='11759856')b on b.卡号1=a.卡号2 
union all
select 卡号1,卡号2,level as 层次,操作员,操作日期 from T_客户层次结构表 a,@t_level b 
where a.卡号1=b.id and 卡号2 is not null and 卡号2='11759856'

解决方案 »

  1.   

    create table tb(卡号1 int,卡号2 int,层数 int)
    insert into tb select 11992354,11737870,2 
    insert into tb select 12071238,11737884,2 
    insert into tb select 11992261,11746354,2 
    insert into tb select 11991892,11746421,2 
    insert into tb select 11992778,11746736,2 
    insert into tb select 11991906,11746747,2 
    insert into tb select 11991947,11746839,2 
    insert into tb select 12071230,11758017,2 
    insert into tb select 12071416,11758017,2 
    insert into tb select 11993048,11758327,2 
    insert into tb select 11993049,11758327,2 
    insert into tb select 12015766,11758849,2 
    insert into tb select 11992394,11759005,2 
    insert into tb select 11992983,11759042,2 
    insert into tb select 11992291,11759668,2 
    insert into tb select 11992292,11759668,2 
    insert into tb select 12071284,11759856,2 
    insert into tb select 12069922,12071284,3 
    select * from tb where 卡号2=11759856
    union all select * from tb where 卡号2 in (select 卡号1 from tb where 卡号2=11759856)
    /*
    卡号1         卡号2         层数
    ----------- ----------- -----------
    12071284    11759856    2
    12069922    12071284    3
    */
    go
    drop table tb