SQL Server : left join results in fewer rows than in left table

扶醉桌前 提交于 2020-01-01 08:25:51

问题


I am using SQL Server (I believe it is 2005).

I have TableA that has 2 columns and 439 rows (each row is unique).

+----------+
|ID | Name |
+----------+

I have TableB that has 35 columns and many hundreds of thousand rows (each row is also unique).

+------------------------------------------------------------------------------+
|Date | ID | Name | Blah1 | Blah2 | ... | Hour1 | Hour2 | Hour3 | ... | Hour24 |
+------------------------------------------------------------------------------+

Each row in TableB has hourly observations and some other house keeping information. Now for testing purposes I am only interested in today's date i.e 4/19/2013.

If I do:

Select count(*) 
from TableB 
where Date = '4/19/2013 12:00:00 AM'

I get 10526, which is correct as there are 10526 distinct locations for which there is hourly observation data each day.

I want to LEFT JOIN TableA and TableB on a.id = b.id, which SHOULD produce a result that has 439 rows.

Unfortunately, the result has 246 rows. How can this be? Isn't a LEFT JOIN suppose to return all rows in TableA regardless of whether there was a match in TableB?

*EDIT*

The complete query I used was:

select * 
from TableA as a
left join TableB as b on a.id = b.id 
where RealDate = '4/20/2013 12:00:00 AM'

回答1:


Try this:

select * from TableA as a
left join (SELECT * from TableB where RealDate = '4/20/2013 12:00:00 AM') as b
on a.id = b.id 

Or this:

select * from TableA as a
left join TableB as b on (a.id = b.id AND RealDate = '4/20/2013 12:00:00 AM')


来源:https://stackoverflow.com/questions/16116559/sql-server-left-join-results-in-fewer-rows-than-in-left-table

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