I want only records in Table A that have disabled= 0 LEFT JOINed to Table B.
Below query returns a record from table A that I don't even want considered when joining to table B. It returns a row even though it's Disabled Flag = 1.
insert into #SOURCETABLE (ID , DisableFlag)
values (3,1)
insert into #TARGETTABLE (ID, Statecode)
values (3,1)
select 'SOURCETABLE' as tablename, *
from #SOURCETABLE
select 'TARGETTABLE' as tablename, *
from #TARGETTABLE
Select A_ID = a.ID
,a.DisableFlag
,B_ID = b.ID
,b.statecode
From #SOURCETABLE A
Left Join #TARGETTABLE B
on a.ID = b.ID
AND a.DisableFlag = 0
Returns
ID DisableFlag ID statecode
3 1 NULL NULL
--Quote me
you don't have any filtering on #SOURCETABLE - you only filter on the join, so all records from #SOURCETABLE will be selected.
and the only record you have on the sample data only has disableflag = 1 so that is what is showing, and the join is returning null as on the join you only look for where #SOURCETABLE disableflag = 0
February 3, 2020 at 12:33 am
So left join just brings over everything *no matter what* filters I put on the A table on the AND?
I see that appears how it works. I added another row to A table and then the AND filter controls which of the rows the bottom table will attempt to align to, but everything from LEFT TABLE is returned, no matter what
drop table if exists #SOURCETABLE
create table #SOURCETABLE (
ID int,
DisableFlag int
)
drop table if exists #TARGETTABLE
create table #TARGETTABLE (
ID int,
Statecode int
)
insert into #SOURCETABLE (ID , DisableFlag)
values (3,1),(2,0)
insert into #TARGETTABLE (ID, Statecode)
values (3,1), (2,0)
select 'SOURCETABLE' as tablename, *
from #SOURCETABLE
select 'TARGETTABLE' as tablename, *
from #TARGETTABLE
Select A_ID = a.ID
,a.DisableFlag
,B_ID = b.ID
,b.statecode
From #SOURCETABLE A
Left Join #TARGETTABLE B
on a.ID = b.ID
and a.DisableFlag = 1
and b.Statecode = 1
--Quote me
February 3, 2020 at 1:01 am
you need to understand how filtering can be done - and the order it happens. and the difference between being a inner or a outer join
February 3, 2020 at 11:30 am
if i'm reading this correctly - just turn it into an inner join
and for code clarity move the disabledflag=0 into the where clause... it has no place in the join
MVDBA
February 6, 2020 at 11:35 am
+1 Agree
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply