简体   繁体   中英

MSSQL - LEFT join with nulls in RIGHT table

I have two tables, tblClient and tblBill which are joined on cltID. Some cltID in tblClient don't have records in tblBill. I want to return all records from tblClient and join tblBill records which are within a date range. If they don't have tblBill records I still want to return that tblClient record.

I'm running:

select *
from tblClient left outer join tblBill
on tblClient.cltID = tblBill.cltid
where tblbill.billDtm between @dtStart and @dtEnd
or tblbill.billDtm is null

If I take out the WHERE clause it returns everything. If I add it back it only returns the records which have a record in tblBill.

This is killing me and I'm sure I'm missing something stupid... Hoping someone can help?

The condition is being applied to the joined results, rather than the table first. If you put your condition as part of the JOIN, you'll limit the tblBill records to your condition and then join to the client table.

SELECT *
FROM   tblClient 
       LEFT JOIN tblBill
         ON tblClient.cltID = tblBill.cltid
            AND tblbill.billDtm between @dtStart and @dtEnd

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