急求一条sql语句,急等!!!
有三张表
A: a , b , c , d
B: b, b1
C: c , c1
查询A, A和其他两张表关联, 如果A中的c=-1,A 和C 不关联,否则关联 C 表
例如:
A:
11 2 3 aa
12 2 -1 ss
B:
2 bb
C:
3 cc
result:11 bbcc aa
12 bb ss
------解决方案--------------------WITH TAB1 AS
(SELECT 11 ID1, 2 ID2, 3 ID3, 'aa' NAME
FROM DUAL
UNION ALL
SELECT 12, 2, -1, 'ss' FROM DUAL),
TAB2 AS
(SELECT 2 ID2, 'bb' NAME FROM DUAL),
TAB3 AS
(SELECT 3 ID3, 'cc' NAME FROM DUAL)
SELECT A.ID1, DECODE(A.ID3, -1, B.NAME, B.NAME || C.NAME), A.NAME
FROM TAB1 A
JOIN TAB2 B
ON A.ID2 = B.ID2
LEFT JOIN TAB3 C
ON A.ID3 = C.ID3
;
------解决方案--------------------这是一个外关联查询
select a.A字段,a.B字段,C.B字段,a.A字段 from
(select A.A字段,B.B字段,A.A字段 from A,B where a.B字段=B.A字段) a,C
where a.C字段=C.A字段(+)