I have two database tables, Categories and SuperCategories, for an inventory control system I’m working on:
Categories: ID_Category, CategoryName
SuperCategories: ID_SuperCategory, CategoryID, SuperCategoryID
I’m putting category-subcategory relationships into the SuperCategories table. I’m putting all categories into the Categories table.
Here is an example:
Categories: ID_Category CategoryName 1 Box 2 Red Box 3 Blue Box 4 Blue Plastic Box 5 Can 6 Tin Can
SuperCategories: ID_Super CategoryID SuperCategoryID 1 2 1 2 3 1 3 4 3 4 6 5
CategoryID and SuperCategoryID relate back to the primary key ID_Category in the Categories table.
What I would like is a query that returns all of the category names that are not parents of any other categories:
Red Box
Blue Plastic Box
Tin Can
This amounts to finding all values of ID_Category that do not show up in the SuperCategoryID column (2, 4, and 6), but I’m having trouble writing the SQL.
I’m using VB6 to query an Access 2000 database.
Any help is appreciated. Thanks!
EDIT: I voted up everyone’s answer that gave me something that worked. I accepted the answer that I felt was the most instructive. Thanks again for your help!
Mike Pone’s answer works, because he joins the ‘Categories’ table with the ‘SuperCategories’ table as a ‘LEFT OUTER JOIN’ – this will take all entries from ‘Categories’ and add columns from ‘SuperCategories’ to those where the link exists – where it does not exist (e.g. where there is no entry in ‘SuperCategories’), you’ll get NULLs for the SuperCategories columns – and that’s exactly what Mike’s query then checks for.
If you would write the query like so:
you would get something like this:
So this basically gives you your answer – all the rows where the ID_Super on the LEFT OUTER JOIN is NULL are those who don’t have any entries in the SuperCategories table. All clear? 🙂
Marc