外部连接不显示额外条目
Outer join not showing extra entries
我做了一个查询,其中使用了 3 个 table。第一个 table 包含我需要的所有名称。第二个和第三个 table 给我那些有账单金额的名字。但我还需要第一个 table 中的所有名称。
SELECT a.name,
nvl(c.bill_amount,0)
FROM table_1 a left outer join table_2 b
ON a.name = b.name
left outer join table_3 c on B.phone_number = C.phone_number
AND B.email = C.email
where b.status = 'YES'
and a.VALID = 'Y';
现在,tables b 和 c 给我的名字数量有限,假设有 5 个在哪个账单上。但是在table_1中,有10个名字。我想在他们的名字上也显示 0 bill_amount。我正在使用 Oracle。
在右侧故事上应用 where
子句基本上使其成为内部联接。要保留它OUTER
,请将条件放入连接条件
尝试:
SELECT a.name,
nvl(c.bill_amount,0)
FROM table_1 a
left outer join table_2 b
ON a.name = b.name
and b.status = 'YES' -- Put it here
left outer join table_3 c
on B.phone_number = C.phone_number
AND B.email = C.email
where a.VALID = 'Y'; -- Only items from the left hand table should go in the where clause
上面的答案是正确的,我只是想更准确一点。事实上,当左连接不匹配时,右手的列 table 被设置为 NULL
.
实际上 NULL 总是在 SQL 中传播值,因此如果连接不进行数学运算,则 b.status = 'YES'
具有值 NULL
,然后谓词也不匹配。
处理此问题的一般方法是 (b.status = 'YES' or b.name IS NULL)
:因为 b.name
是连接列,当且仅当连接不匹配时它才为空,而 [= 可能不是这种情况15=].
因为 NULL
正在传播,所以您不能使用 field = NULL
,而是 field IS NULL
。
但是在连接子句中更清楚时也可以。
我做了一个查询,其中使用了 3 个 table。第一个 table 包含我需要的所有名称。第二个和第三个 table 给我那些有账单金额的名字。但我还需要第一个 table 中的所有名称。
SELECT a.name,
nvl(c.bill_amount,0)
FROM table_1 a left outer join table_2 b
ON a.name = b.name
left outer join table_3 c on B.phone_number = C.phone_number
AND B.email = C.email
where b.status = 'YES'
and a.VALID = 'Y';
现在,tables b 和 c 给我的名字数量有限,假设有 5 个在哪个账单上。但是在table_1中,有10个名字。我想在他们的名字上也显示 0 bill_amount。我正在使用 Oracle。
在右侧故事上应用 where
子句基本上使其成为内部联接。要保留它OUTER
,请将条件放入连接条件
尝试:
SELECT a.name,
nvl(c.bill_amount,0)
FROM table_1 a
left outer join table_2 b
ON a.name = b.name
and b.status = 'YES' -- Put it here
left outer join table_3 c
on B.phone_number = C.phone_number
AND B.email = C.email
where a.VALID = 'Y'; -- Only items from the left hand table should go in the where clause
上面的答案是正确的,我只是想更准确一点。事实上,当左连接不匹配时,右手的列 table 被设置为 NULL
.
实际上 NULL 总是在 SQL 中传播值,因此如果连接不进行数学运算,则 b.status = 'YES'
具有值 NULL
,然后谓词也不匹配。
处理此问题的一般方法是 (b.status = 'YES' or b.name IS NULL)
:因为 b.name
是连接列,当且仅当连接不匹配时它才为空,而 [= 可能不是这种情况15=].
因为 NULL
正在传播,所以您不能使用 field = NULL
,而是 field IS NULL
。
但是在连接子句中更清楚时也可以。