2个表
table1 table2
编号 姓名 编号1, 编号2,收入
ad1 张2 ad5 th2 12
th2 张1 ad1 th1 32
ad2 张3 ad3 th3 56
th3 张4 ad4 th4 78现在想写一个语句
先用table2的“编号1”字段和table1的“编号”字段匹配出姓名
如果“编号1”没有匹配成功就用“编号2”和table1的“编号”字段去匹配
查询的结果格式是
编号1, 编号2,收入,姓名
ad5 th2 12 张1
ad1 th1 32 张2
ad3 th3 56 张4
ad4 th4 78
求怎么写sql查询语句,非常感谢!!!
table1 table2
编号 姓名 编号1, 编号2,收入
ad1 张2 ad5 th2 12
th2 张1 ad1 th1 32
ad2 张3 ad3 th3 56
th3 张4 ad4 th4 78现在想写一个语句
先用table2的“编号1”字段和table1的“编号”字段匹配出姓名
如果“编号1”没有匹配成功就用“编号2”和table1的“编号”字段去匹配
查询的结果格式是
编号1, 编号2,收入,姓名
ad5 th2 12 张1
ad1 th1 32 张2
ad3 th3 56 张4
ad4 th4 78
求怎么写sql查询语句,非常感谢!!!
select b.编号1, b.编号2, b.收入, a.姓名 from table1 a, table2 b where a.编号=b.编号1 or a.编号=b.编号2反正你的编号如果在编号1中就不在编号2中,任意匹配一个就好了
right join #t2 b on 编号=
case when (select count(1) from #t1 where 编号=b.编号1)>0
then 编号1 else 编号2 end
union all
select b.编号1, b.编号2, b.收入, a.姓名 from table1 a, table2 b where a.编号=b.编号2
insert into table1 select 'th2', '张1'
insert into table1 select 'ad2', '张3'
insert into table1 select 'th3', '张4'
create table table2 (bh1 varchar(10),bh2 varchar(10),sl int)insert into table2 select 'ad5' , 'th2', 12
insert into table2 select 'ad1' , 'th1', 32
insert into table2 select 'ad3' , 'th3', 56
insert into table2 select 'ad4' , 'th4', 78
select B.*,A.xm from table1 A right join table2 B on (A.bh = B.bh1 or A.bh = B.bh2)/*
bh1 bh2 sl xm
------------------
ad5 th2 12 张1
ad1 th1 32 张2
ad3 th3 56 张4
ad4 th4 78 NULL*/drop table table1,table2
insert into table1 select 'th2', '张1'
insert into table1 select 'ad2', '张3'
insert into table1 select 'th3', '张4'
create table table2 (bh1 varchar(10),bh2 varchar(10),sl int)insert into table2 select 'ad5' , 'th2', 12
insert into table2 select 'ad1' , 'th1', 32
insert into table2 select 'ad3' , 'th3', 56
insert into table2 select 'ad4' , 'th4', 78select a.*,b.xm from table2 a
left join table1 b
on case when a.bh1=b.bh then a.bh1
else a.bh2
end =b.bh
--结果/*
bh1 bh2 sl xm
---------- ---------- ----------- --------------------
ad5 th2 12 张1
ad1 th1 32 张2
ad3 th3 56 张4
ad4 th4 78 NULL(所影响的行数为 4 行)
*/