Oracle join未按预期工作

时间:2013-11-21 23:29:36

标签: sql oracle

我在两个表上运行左外连接,但获取的结果不是预期的。我已经给出了以下示例:

当我在个别tavles上运行条件时,以下是计数。

select count(*) from TableA 
where ColumnA= 'X'
and ColumnB like 'ABC'

--Count 10000

select count(*) from TableB 
where ColumnD in ('hello','there')

--Count 7350

select count(*) from TableA ta
LEFT JOIN TableB tb
on ta.ColumnM = tb.ColumnN
where ta.ColumnA= 'X'
and ta.ColumnB like 'ABC'
and tb.ColumnD in ('hello','there')

Expected Count - 10000
Actual Count - 7300

我假设我对连接的理解在这种情况下是不正确的。谁能解释这种行为,让我知道我哪里出错了?

2 个答案:

答案 0 :(得分:4)

外连接表(where)上的tb.ColumnD in ('hello','there')条件将外连接转回内连接。

您需要在join子句中应用该条件:

select count(*) 
from TableA ta
  LEFT JOIN TableB tb 
         on ta.ColumnM = tb.ColumnN
        and tb.ColumnD in ('hello','there')
where ta.ColumnA= 'X'
  and ta.ColumnB like 'ABC'

答案 1 :(得分:3)

您期望返回10k行的原因是左连接应该为第一个表中的每个人生成一行。当它没有找到一行时,它会产生一个null,你将使用这个子句删除它:

and tb.ColumnD in ('hello','there')

如果你想要10k行,请在jouin之前应用表b上的where子句,而不是之后:

select count(*) from TableA ta
LEFT JOIN (select * from TableB  tb.ColumnD in ('hello','there') ) tb
on ta.ColumnM = tb.ColumnN
where ta.ColumnA= 'X'
and ta.ColumnB like 'ABC'

编辑...这样做效果更好,感谢评论:

select count(*) from TableA ta
LEFT JOIN TableB tb
on ta.ColumnM = tb.ColumnN and  tb.ColumnD in ('hello','there')
where ta.ColumnA= 'X'
and ta.ColumnB like 'ABC'
相关问题