2017-11-18 101 views
0

我試圖獲取硬編碼事件的列表,並將其與實際事件加入表中,以便實際查看它們是否已執行。Oracle左外連接返回0行,其中包含左數據集中的數據

這裏是我的查詢:

SELECT a.Verification FROM (SELECT 'Verify ID changed' as Verification FROM DUAL 
UNION ALL 
SELECT 'Verify manual Valve closed' as Verification FROM DUAL 
UNION ALL 
SELECT 'Verify manual Valve open' as Verification FROM DUAL 
UNION ALL 
SELECT 'Visually verify Things' as Verification FROM DUAL 
) a 
LEFT OUTER JOIN JOBEVENTS c ON a.Verification = c.EVENTDESC 
WHERE c.EVT_TIME BETWEEN '22-Jan-2017' AND '22-Jan-2017' 

當我閱讀文檔的左外連接,那麼隊列應始終從返回左表中的數據,那麼,爲什麼我的查詢返回0行(沒有什麼在JOBEVENTS事件表中,但是硬編碼值始終存在)。

我誤解了LEFT OUTER JOIN的工作原理嗎?

+0

您的Where子句依賴於來自左連接的數據。如果左連接不匹配,那麼您的where子句也將無法匹配。 –

回答

1

在連接的左側連接表部分創建過濾器,而不是where子句。

SELECT a.Verification, c.* 
FROM (
     SELECT 'Verify ID changed' as Verification FROM DUAL UNION ALL 
     SELECT 'Verify manual Valve closed' as Verification FROM DUAL UNION ALL 
     SELECT 'Verify manual Valve open' as Verification FROM DUAL UNION ALL 
     SELECT 'Visually verify Things' as Verification FROM DUAL 
    ) a 
LEFT OUTER JOIN JOBEVENTS c ON a.Verification = c.EVENTDESC 
     AND c.EVT_TIME BETWEEN '22-Jan-2017' AND '22-Jan-2017' 
; 

或者,您可以添加到您的where子句,以便可以從左連接表返回NULLS。例如:

SELECT a.Verification, c.* 
FROM (
     SELECT 'Verify ID changed' as Verification FROM DUAL UNION ALL 
     SELECT 'Verify manual Valve closed' as Verification FROM DUAL UNION ALL 
     SELECT 'Verify manual Valve open' as Verification FROM DUAL UNION ALL 
     SELECT 'Visually verify Things' as Verification FROM DUAL 
    ) a 
LEFT OUTER JOIN JOBEVENTS c ON a.Verification = c.EVENTDESC 
WHERE (c.EVT_TIME BETWEEN '22-Jan-2017' AND '22-Jan-2017' 
     OR c.EVENTDESC IS NULL 
    ) 
; 

您從該表允許空值在where子句中引用時務必小心與外連接表,否則你創建一個內部的等價條件加入(&有時被稱爲「隱含的內部聯接」) 。