1

我必须使用每个 col (id) 的表 (tbla 和 tblb):

从 tbla 中选择 *;

ID
---
1
3
5#A

select * from tblb;

ID
---
2
3

现在我需要一个完整的加入:

select a.id, b.id
from tbla a
full outer join tblb b on b.id = a.id;

ID  ID1
--------
1   
3   3
5#A 
    2

...但在 tbla.id 中没有包含 #-sign 的条目

select a.id, b.id
from tbla a
full outer join tblb b on b.id = a.id
where a.id not like '%#%';

ID  ID1
--------
1   
3   3

为什么 tblb 中 id 为 2 的条目丢失了?

4

3 回答 3

3

因为当您执行 a 时full outer join,任一侧的列都可能以一个NULL值结束。

显式检查 NULL:

select a.id, b.id
from tbla a
full outer join tblb b on b.id = a.id
where a.id not like '%#%' or a.id is null;

(最初,我建议将逻辑移至on子句。唉,full outer join即使没有记录与条件匹配,两个表中的记录也会保留。因此,将条件移至on子句并不能解决任何问题。)

于 2013-05-06T14:52:28.840 回答
0

当您进行外部连接时,您必须在 from 子句中进行过滤。如果您在 where 子句中执行此操作,则您的联接有效地成为内部联接。

所以改变这个:

full outer join tblb b on b.id = a.id
where a.id not like '%#%'

对此

full outer join tblb b on b.id = a.id
and a.id not like '%#%'
于 2013-05-06T14:53:06.553 回答
0

您正在执行完全联接,但通过在 where 子句中指定 a.id,您可以在之后过滤结果集。

要实现您想要的,您可以将子句移动到连接条件中:

select a.id, b.id
from tbla a
full outer join tblb b 
  on b.id = a.id
  and a.id not like '%#%';

或者你可以使用 nvl:

select a.id, b.id
from tbla a
full outer join tblb b on b.id = a.id
where nvl(a.id, 'n/a') not like '%#%';

或者明确允许 a.id 的 NULL 值:

select a.id, b.id
from tbla a
full outer join tblb b on b.id = a.id
where (a.id is null or a.id not like '%#%');
于 2013-05-06T14:54:12.070 回答