开发者

left outer join with a where in sql query

开发者 https://www.devze.com 2023-04-08 15:06 出处:网络
i have a sql query like this: select something from ( inner query here - outputs is correct: eg 200开发者_运维知识库0 datasets

i have a sql query like this:

    select something
from
(
inner query here - outputs is correct: eg 200开发者_运维知识库0 datasets
) as a

left outer join tableA
on tableA.id=innerQuery.id
where  someYear = -----------> had to change this "and" to "where"
(
select max(tableYear)
from tableC
where
etc....
)

eg years:
2011, 1999, 1901 max is 2011.
1978, 1981,1990 max is 1990.

etc.. the problem i am having is, with the "where" statement, i am only getting fewer 1600 datasets; however if i were to key in a value and use "and", outputs comes out correct 2000. is there a way to use "where" with a left outer join and get all my outputs?


If you test a column from a LEFT JOINed table in the WHERE clause, you force that join to behave as if it were an INNER JOIN. The correct method is to make that test part of the join condition.


In a LEFT JOIN, it makes a difference whether you put the filter into the JOIN clause or into the WHERE clause.

I explained the difference very detailed here:
What is the difference in these two queries as getting two different result set?

To summarize it in one sentence:
if you want the full 2000 rows and not just 1600, you have to put the filter in the JOIN clause.


Why not leave the condition as part of the join (as you have posted? somedate must be from the right table i.e. tableA and so it may be null. So if you want to get all the results, you have to account for that e.g.

IsNull(somedate, '1/1/2000') = '1/1/2000'

or

(somedate = '1/1/2000' OR somedate is null)
0

精彩评论

暂无评论...
验证码 换一张
取 消