oracle 多個with as
阿新 • • 發佈:2018-12-20
今天去面試,遇到一個問題。
題目是這樣的:
表1:
SQL> select * from tb_data; ID CODE1 CODE2 ---------- ---------- ---------- 1 1 2 2 2 1 3 2 3 4 3 1 5 4 2 6 5 3 已選擇6行。 SQL>
表2:
SQL> select * from tb_code;
CODE DESCRIPTION
---------- --------------------
1 a
2 b
3 c
4 d
5 e
SQL>
要求顯示成:
ID DESCRIPTION DESCRIPTION ---------- -------------------- -------------------- 1 a b 2 b a 3 b c 4 c a 5 d b 6 e c
也就是把表1裡的code翻譯成表2裡的description。
因為面試官就坐在旁邊,以前沒寫過,也沒怎麼動腦筋去寫。
現在回來後,就想了一下。可以用多個with as來解決。
WITH T3 AS ( SELECT T1.ID, T1.CODE1, T2.DESCRIPTION FROM TB_DATA T1, TB_CODE T2 WHERE T1.CODE1 = T2.CODE ), T4 AS ( SELECT T1.ID, T1.CODE2, T2.DESCRIPTION FROM TB_DATA T1, TB_CODE T2 WHERE T1.CODE2 = T2.CODE ) SELECT T3.ID, T3.DESCRIPTION, T4.DESCRIPTION FROM T3, T4 WHERE T3.ID = T4.ID ORDER BY ID;
執行後:
SQL> WITH
2 T3 AS
3 (
4 SELECT T1.ID, T1.CODE1, T2.DESCRIPTION
5 FROM TB_DATA T1, TB_CODE T2
6 WHERE T1.CODE1 = T2.CODE
7 ),
8 T4 AS
9 (
10 SELECT T1.ID, T1.CODE2, T2.DESCRIPTION
11 FROM TB_DATA T1, TB_CODE T2
12 WHERE T1.CODE2 = T2.CODE
13 )
14 SELECT T3.ID, T3.DESCRIPTION, T4.DESCRIPTION
15 FROM T3, T4
16 WHERE T3.ID = T4.ID
17 ORDER BY ID;
ID DESCRIPTION DESCRIPTION
---------- -------------------- --------------------
1 a b
2 b a
3 b c
4 c a
5 d b
6 e c
已選擇6行。
SQL>