In sql server 2008, I have the following query:
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 and i.siteid = 132
where (ic.isactive = 1 or ic.isactive is null)
order by c.title, s.title
I am trying to get items in their subcategories, but I still want to return a record if there are no items in the category or subcategory. Subcategories that have no items are never returned. What am I doing wrong?
Thank you
EDIT
Modified query with a second left join and where clause, but it’s still not returning nulls. :/
EDIT 2
Moved siteid to item left join. When I do this I get way more records than expected. Some items have a null siteid and I only want to included them when they have a specific id.
EDIT 3
Table structure:
Categories Table
-------
CategoryID
Title
SubCategories Table
-------
SubCategoryID
CategoryID
Title
ItemCategories Table
-------
ItemCategoryID
ItemID
SubCategoryID
IsActive
Items Table
--------
ItemID
Title
SiteID
change
join items i… toLEFT join items i… and your query should work as you expect.EDIT
You can not filter LEFT JOIN tables in the where clause unless you account for nulls, because the left join allows those columns to have a value or be null when no rows matches:
and i.siteid = 132will throw away any of your rows that have a NULLi.siteid, where none existed. Move this to the ON:left join items i on ic.itemid = i.itemid and i.siteid = 132or make the WHERE handle NULLs:
WHERE ... AND (i.siteid = 132 OR i.siteid IS NULL)EDIT based on OP’s edit 3
I’m not 100% sure what the OP is after, this will return all info that can be joined when the
siteid=132as given in the questionOUTPUT:
This will list all categories, even if there is no match to the
siteid=132OUTPUT: