sql left join returns

风格不统一 提交于 2019-12-11 04:07:44

问题


I am trying to run a left join on 2 tables. I do not have a group by and the only where condition i have is on the second table. But, the returned rows are less than the first table. isn't the left join suppose to bring all the data from the first table? Here is my SQL:

select * 
  from tbl_a A left join tbl_b B
     ON
       A.Cnumber=B.Cnumber
       and A.CDNUmber=B.CDNumber
       and abs(A.duration - B.Duration)<2
       and substr(A.text,1,3)||substr(A.text,5,8)||substr(A.text,9,2)=substr(B.text,1,8)
where B.fixed = 'b580'

There are 140,000 records in table A but the result returned is less than 100,000 records. What is the problem and how can I solve it?


回答1:


As soon as you put a condition in the WHERE clause that references the right table and doesn't accommodate the NULLs that will be produced when the join is unsuccessful, you've transformed it (effectively) back into an INNER JOIN.

Try:

where B.fixed = 'b580' OR B.fixed IS NULL

Or add this condition to the ON clause for the JOIN.




回答2:


You should add the where clause to the join:

select * 
  from tbl_a A left join tbl_b B
     ON
       A.Cnumber=B.Cnumber
       and A.CDNUmber=B.CDNumber
       and abs(A.duration - B.Duration)<2
       and substr(A.text,1,3)||substr(A.text,5,8)||substr(A.text,9,2)=substr(B.text,1,8)
  and B.fixed = 'b580'

If you use where statemen all records where b is not existing will not returned.



来源:https://stackoverflow.com/questions/28039591/sql-left-join-returns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!