Why is my left join not returning nulls?

后端 未结 6 1412
半阙折子戏
半阙折子戏 2020-12-05 18:31

In sql server 2008, I have the following query:

select      
    c.title as categorytitle,
    s.title as subcategorytitle,
    i.title as itemtitle
from cat         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 18:40

    2nd attempt, I think I got your problem now. If I understand correctly then what happens is that you end up with two kind of NULLs in SiteID in your case (the case when you see 10,000e results, but that is still on the right track).

    There are NULLs that come from left join and the ones that come from actual Item table siteid. You want to have the ones that come from left join, but don't want the ones from data.

    This is a very common mistake with outer joins when testing for existence of matched rows.

    Keep in mind that you if you want unmatched rows that should always test for NULL only on the columns which are defined as NOT NULL (primary key from the outer table is a natural candidate here). Otherwise you can not distinguish between the rows that are NULL due to LEFT join and rows which would be NULL even if it was an INNER join

    At least two ways to go about this: a) left join on subquery that will filter out rows with siteid is null before the left join kicks in
    b) rewrite criteria (assuming ItemID is required in Items) to say

    select      
        c.title as categorytitle,
        s.title as subcategorytitle,
        i.title as itemtitle
    from categories c
    join subcategories s on c.categoryid = s.categoryid
    left join itemcategories ic on s.subcategoryid = ic.subcategoryid 
    left join items i on ic.itemid = i.itemid
    where (ic.isactive = 1 or ic.isactive is null) AND (i.siteid = 132 or i.itemid is null)
    order by c.title, s.title
    

    (I am assuming that the query up to the join to items table was giving you what you expected).

    If itemid is required in items then the above condition says - rows with siteid 132 or rows that really come from unmatched left join (do note that the condition is on i.itemid is null and not i.siteid is null).

提交回复
热议问题