A表中字段为
A_ID,B_ID1,B_ID2,ATYPE
1, 1, 2, 1
2, 1, 3, 2
3, , ,3
4,, 2, 4
5,,,5
6 ,4,, 6
B表中字段为
B_ID,B_NAME
1 LIU
2 KAI
3 AAA
4 BBB
5 CCC
A表中B_ID1,B_ID2都是B表的外键;
我需要的结果为:
A_ID,B_NAME1,B_NAME2,ATYPE
1 ,LIU, KAI, 1
2 ,LIU, AAA, 2
3 ,,,3
4 ,,KAI, 4
5 ,,,5
6, BBB,, 6
语句怎么查询呢?
------最佳解决方案--------------------
select a.A_ID ,(select b.BNAME from B b where b.B_ID=a.A_ID1),(select b.BNAME from B b where b.B_ID=a.A_ID2) ,a.ATYPE from A a;
------其他解决方案--------------------
SELECT T1.A_ID,NVL(T2.B_NAME,'') AS B_NAME1,NVL(T3.B_NAME,'') AS B_NAME2,T1.ATYPE FROM A T1 LEFT JOIN B T2 ON T1.B_ID1 = T2.B_ID LEFT JOIN B T3 ON T1.B_ID2 = T3.B_ID ORDER BY T1.A_ID
------其他解决方案--------------------
select A_ID,b1.B_NAME B_NAME1,b2.B_NAME B_NAME2,ATYPE from a,b b1,b b2
where a.B_ID1=b1.B_ID(+)
and a.B_ID2=b2.B_ID(+)
------其他解决方案--------------------
with a as(
select 1 a_id,1 b_id1,2 b_id2,1 atype from dual
union all
select 2,1,3,2 from dual
union all
select 3,null,null,3 from dual
union all
select 4,null,2,4 from dual
union all
select 5,null,null,5 from dual
union all
select 6,4,null,6 from dual
),b as(
select 1 b_id,'LIU' b_name from dual
union all
select 2,'KAI' from dual
union all
select 3,'AAA' from dual
union all
select 4,'BBB' from dual
union all
select 5,'CCC' from dual
)
SELECT A_ID,(SELECT B_NAME FROM B WHERE B_ID=A.B_ID1) B_ID1,(SELECT B_NAME FROM B WHERE B_ID=A.B_ID2) B_ID2,ATYPE FROM A
A_ID B_ID1 B_ID2 ATYPE
---------- ----- ----- ----------
1 LIU KAI 1
2 LIU AAA 2
3 3
4 KAI 4
5 5
6 BBB 6