2012-12-22 41 views
1

我想要兩個列表,它們都顯示來自其各自表的未使用其他表的記錄。創建一個視圖,顯示兩個具有特定值的列表

兩個列表,一個用於表a_aif和一個用於表a_proxy。列表只顯示那些列中不存在的那些fee_source_id'sa_fees.fee_source

這是我到目前爲止(兩個單獨的查詢)。任何方式使這兩個列表在單獨的列中查看?

SELECT a_aif.fee_source_id 
FROM a_aif, a_fees 
WHERE a_fees.fee_source NOT IN (SELECT a_aif.fee_source_id); 

SELECT a_proxy.fee_source_id 
FROM a_proxy, a_fees 
WHERE a_fees.fee_source NOT IN (SELECT a_proxy.fee_source_id); 
+0

您正在使用什麼RDBMS? –

+0

@MichaelBerkowski這是在他的標題,我把它轉移到標籤。 – Barmar

+0

@Barmar謝謝我錯過了標題 –

回答

0

這個方法應該對你正在使用的RDBMS非常不可知。

一對LEFT JOIN從您選擇的記錄,其中右側是NULL將做。 A UNION查詢用於構建來自a_aifa_proxy表的ID的主列表。

SELECT 
    full_list.fee_source_id, 
    CASE WHEN aif_fee_source_id IS NOT NULL THEN 'present' ELSE 'not-present' END AS aif, 
    CASE WHEN proxy_fee_source_id IS NOT NULL THEN 'present' ELSE 'not-present' END AS proxy 
FROM (
    /* UNION list gets total list of ids from both tables */ 
    SELECT fee_source_id FROM a_aif 
    UNION SELECT fee_source_id FROM a_proxy 
) full_list 
LEFT JOIN (
    /* First subquery joins to get ids not present in a_aif */ 
    SELECT fee_source_id AS aif_fee_source_id 
    FROM 
    a_aif 
    LEFT JOIN a_fees ON a_aif.fee_source_id = a_fees.fee_source 
) aif ON full_list.fee_source_id = aif_fee_source_id 
LEFT JOIN (
    /* Second subquery joins to get ids not present in a_proxy */ 
    SELECT fee_source_id AS proxy_fee_source_id 
    FROM 
    a_proxy 
    LEFT JOIN a_fees ON a_proxy.fee_source_id = a_fees.fee_source 
) proxy ON full_list.fee_source_id = proxy.proxy_fee_source_id 

http://sqlfiddle.com/#!2/cc170/3

相關問題