I am trying to find the parent categories.
Therefore i need to write,
where CategoryID HAS a ParentCategoryID of 0
CategoryID could be 30 but if it has a ParentCategoryID of 0 then you know its the parent category.
This is my SQL so far:
SELECT CategoryID, ParentCategoryID, Name, Published, Deleted, PictureID
FROM Nop_Category
WHERE (Deleted = 0)
AND (Published = 1)
AND (CategoryID = ParentCategoryID = 0)
To perform equality checks against two fields, use the AND operator and specify the fieldname twice.
But you could also write it like so and achieve the same results:
However, in your question, you mentioned that CategoryID could be 30, so your query won’t work. You’ll likely want to leave out the CategoryID or specify a specific categoryId through a parameter:
EDIT:
Generally when I do self-related tables, I use NULL for the ParentId which tells me that the current row is the parent. If you’re using 0 for null, then a record with a CategoryId of 30 and a ParentCategoryId of 30 means it’s neather a child nor a parent.
In this scenerio, you can only have 1 top level category, ALL others will be children (even though you consider a ParentCategoryId of 0 a parent, it still must live under CategoryId 0)
Using NULL
In this scenerio, I can easily find ALL top level categories
Or, if I want the top category for a specific category
And my referential integrity is completely in tact.
To locate immediate children of a parent, simply pass in the categoryid of the parent you’re looking for: