Sql Oracle join未按预期工作

Sql Oracle join未按预期工作,sql,oracle,Sql,Oracle,我正在两个表上运行左外部联接,但获取的结果与预期不符。我列举了以下例子: 当我在单个TAVLE上运行条件时,下面是计数 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 Tab

我正在两个表上运行左外部联接,但获取的结果与预期不符。我列举了以下例子:

当我在单个TAVLE上运行条件时,下面是计数

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

我假设我对连接的理解在这种情况下是不正确的。有人能解释一下这种行为并告诉我哪里出了问题吗?

您希望返回10k行的原因是左连接应该为第一个表中的每个人生成一行。当它找不到行时,将生成一个null,您将使用以下子句删除该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'
您在“hello”中的外部联接表tb.ColumnD上的where条件将外部联接变回内部联接

您需要在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'

很好的解释,但是内联视图不是必需的。在“hello”中的ta.column=tb.ColumnN和tb.ColumnD上左键连接tableb tb,“there”可以正常工作