需求及問題
在一些表關聯查詢中,當存在源表和關聯表都有過慮條件(and)時,如果其中一個條件不符合,結果就有可能為空白;
而實際上我們要求結果集中,條件不符合的顯示空,但其它條件正常的,依然要顯示。
1.要達到目的,不符合的資料顯示為空白,符合的照常顯示
2.直接在where裡放入條件,當有一個不符合時,結果集可能為空白
/*需求和問題*//*1.where中放兩個查詢條件,有可能資料集為空白*/selec distinct t t.sec_code, t.sec_sname, decode(t1.chng_pct,null,'--',TO_CHAR(t1.chng_pct,'FM9999999999999990.90')) chng_pct, t.trans_type, t.tradedate from mv_stk_trans_info t left outer join mv_sec_mkt t1 on t.sec_unicode = t1.sec_unicode where t.tradedate=(select max(tradedate) from mv_stk_trans_info ) and t1.tradedate=(select max(tradedate) from mv_stk_trans_info )order by t.sec_code asc;
3.把限制為空白列的條件放到outer join的on中,要報ORA-01799:列不能外部聯結到子查詢的錯
/*2.把限制為空白列的條件放到outer join的on中,要報ORA-01799:列不能外部聯結到子查詢的錯*/select distinct t.sec_code, t.sec_sname, decode(t1.chng_pct,null,'--',TO_CHAR(t1.chng_pct,'FM9999999999999990.90')) chng_pct, t.trans_type, t.tradedate from mv_stk_trans_info t left outer join mv_sec_mkt t1 on t.sec_unicode = t1.sec_unicode and t1.tradedate=(select max(tradedate) from mv_stk_trans_info )where t.tradedate=(select max(tradedate) from mv_stk_trans_info ) order by t.sec_code asc;
解決方案
1.先查詢出關聯表的關聯列,條件列,以及其它需要的列,查詢結果集作為一個表,再讓其它表來關聯這個結果集
/*(推薦)1.先查詢出關聯表的關聯列,條件列,以及其它需要的列,查詢結果集作為一個表,再讓其它表來關聯這個結果集*//*方案1,速度運行為0.938*/select distinct t.sec_code, t.sec_sname, decode(t1.chng_pct,null,'--',TO_CHAR(t1.chng_pct,'FM9999999999999990.90')) chng_pct, t.trans_type, t.tradedate from mv_stk_trans_info t left outer join (select sec_unicode, chng_pct from mv_sec_mkt where tradedate=(select max(tradedate) from mv_sec_mkt)) t1 on t.sec_unicode=t1.sec_unicode where t.tradedate=(select max(tradedate) from mv_stk_trans_info )order by t.sec_code asc;
2.先用一個函數來完成關聯表的限制條件,並返回限制條件,再在outer join的on中加入限制條件
/*2.先用一個函數來完成關聯表的限制條件,並返回限制條件,再在outer join的on中加入限制條件*//*方案2,速度運行為3.922*/--函數返回關聯條件create or replace function fun_getMaxDay return date as v_max_date date;begin select max(tradedate) into v_max_date from mv_stk_trans_info; return v_max_date;end;--關聯查詢select t.sec_code, t.sec_sname, decode(t1.chng_pct,null,'--',TO_CHAR(t1.chng_pct,'FM9999999999999990.90')) chng_pct, t.trans_type, t.tradedate from mv_stk_trans_info t left outer join mv_sec_mkt t1 on t.sec_unicode = t1.sec_unicode and t1.tradedate=fun_getMaxDay where t.tradedate=(select max(tradedate) from mv_stk_trans_info ) order by t.sec_code asc;
方案1.2均能達到目的,但方案1用時少,且方便,推薦1。