SQL Inner Join On Null Values

前端 未结 7 1864
天命终不由人
天命终不由人 2020-12-08 04:16

I have a Join

SELECT * FROM Y
INNER JOIN X ON ISNULL(X.QID, 0) = ISNULL(y.QID, 0) 

Isnull in a Join like this makes it slow.

7条回答
  •  遥遥无期
    2020-12-08 05:02

    I'm pretty sure that the join doesn't even do what you want. If there are 100 records in table a with a null qid and 100 records in table b with a null qid, then the join as written should make a cross join and give 10,000 results for those records. If you look at the following code and run the examples, I think that the last one is probably more the result set you intended:

    create table #test1 (id int identity, qid int)
    create table #test2 (id int identity, qid int)
    
    Insert #test1 (qid)
    select null
    union all
    select null
    union all
    select 1
    union all
    select 2
    union all
    select null
    
    Insert #test2 (qid)
    select null
    union all
    select null
    union all
    select 1
    union all
    select 3
    union all
    select null
    
    
    select * from #test2 t2
    join #test1 t1 on t2.qid = t1.qid
    
    select * from #test2 t2
    join #test1 t1 on isnull(t2.qid, 0) = isnull(t1.qid, 0)
    
    
    select * from #test2 t2
    join #test1 t1 on 
     t1.qid = t2.qid OR ( t1.qid IS NULL AND t2.qid IS NULL )
    
    
    select t2.id, t2.qid, t1.id, t1.qid from #test2 t2
    join #test1 t1 on t2.qid = t1.qid
    union all
    select null, null,id, qid from #test1 where qid is null
    union all
    select id, qid, null, null from #test2  where qid is null
    

提交回复
热议问题