简体   繁体   中英

left outer join with a where in sql query

i have a sql query like this:

    select something
from
(
inner query here - outputs is correct: eg 2000 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 ie tableA and so it may be null. So if you want to get all the results, you have to account for that eg

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM