Oracle左外连接返回0行,左数据集中包含数据

时间:2017-11-18 00:03:18

标签: oracle join

我正在尝试获取硬编码事件列表并加入包含实际事件的表格,因此我实际上可以看到它们是否已执行。

以下是我的问题:

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'

当我阅读LEFT Outer join的文档时,队列应该总是返回左表中的数据,那么为什么我的查询返回0行(JOBEVENTS事件表中没有任何内容,但是左边的硬编码值总是有)。

我误解了LEFT OUTER JOIN的工作原理吗?

1 个答案:

答案 0 :(得分: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。 e.g:

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
      )
;

在允许来自该表的NULLS的where子句中引用时,请始终注意外部联接表,否则您将创建内部联接的等效条件(&有时称为"暗示内部联接")