根據這個網站:http://www.dba-oracle.com/t_convert_set_to_join_sql_parameter.htm,具有不更換MINUS運算符子查詢更快。我希望看到這個證明。無論如何,我使用REGEXP_REPLACE,因爲我對嵌套的INSTR/SUBSTR調用過敏。
首先,我使用WITH子句來設置數據表1和表2作爲原始數據表(當然,您已經有了這些,因此不需要這部分)。注意我在那裏添加了一個嵌入逗號的附加行,以滿足OP中註釋的問題。然後,仍然使用WITH子句,我從相同的數據中創建了T1_converted和T2_converted,但從Table1/ColumnA剝離了前3個字符,並從Table2/ColumnB剝離了前3和後3個字符。這樣做會減少底部實際選擇中所需的REGEXP_REPLACE調用次數,並準備數據以使選擇更容易遵循。注 - 假設總是有3個主要字符在兩個表中剝離,3個尾隨字符剝離在表2中。如果這應該改變,正則表達式將不得不改變。
SQL> -- Simulates original table
SQL> with Table1(ColumnA) as (
2 select 'TZ-ZA112' from dual
3 union
4 select 'TZ-RT322' from dual
5 union
6 select 'TZ-JKAAA' from dual
7 ),
8 -- Simulates original table
9 Table2(ColumnB) as (
10 select 'TZ-ZA112,-2' from dual
11 union
12 select 'TZ-HHASS,-4' from dual
13 union
14 select 'TZ-RT322,4-' from dual
15 union
16 select 'TZ-R,T322,4-' from dual -- make sure commas are handled
17 ),
18 -- Strip leading 3 characters from table 1
19 T1_converted(ColA) as (
20 select regexp_replace(ColumnA, '^.{3}(.*)$', '\1') from Table1
21 ),
22 -- Strip leading and trailing 3 characters from table 2
23 T2_converted(ColB) as (
24 select regexp_replace(ColumnB, '^.{3}(.*).{3}$', '\1') from Table2
25 )
26 -- Get the differences
27 select ColA Unique
28 from T1_converted
29 where (ColA) not in
30 (select ColB from T2_converted)
31 union all
32 select ColB from T2_converted
33 where (ColB) not in
34 (select ColA from T1_converted);
輸出:
Unique
-----------------------------------------------------------------------------
JKAAA
R,T322
HHASS
SQL>
我沒有看到這個值,而不包括具有數據(或丟失數據?)表的名稱,但不是在你的要求,所以我會把它留給你作爲一個練習,以彌補出
前三個字符將始終是'TZ-'? – Nivas
@Nivas不,他們不會,這只是一個例子。 – ceesharpie