1

I have 3 tables

  • Table 1 [StockItem] contains information about an item, I need only the Id from this table

  • Table 2 [Categories] contains the categories and subcategories with their names and URL slug

  • Table 3 [ItemCategories] contains the categories for each item and has only two columns, CategoryId and StockItemId

I have this query which now returns the category id and combined slug as category/subcategory...

WITH categoryPath(Id, Slug)
AS
(
     SELECT 
         Id, Slug 
     FROM 
         Categories
     WHERE 
         ParentCategoryId IS NULL

     UNION ALL

     SELECT 
         Categories.Id
         ,CAST(categoryPath.Slug + '/' + categories.Slug AS NVARCHAR(150))  
     FROM 
         Categories
     JOIN 
         categoryPath ON Categories.ParentCategoryId = categoryPath.Id
)
SELECT * 
FROM ItemCategories
JOIN categoryPath ON ItemCategories.StockId = categoryPath.Id 
WHERE ItemCategories.StockId = 5

The result of this query looks like this:

enter image description here

What I want is to add to the result the Category Name from the [Categories] table which have the column [CategoryName], but I don't know how to add another JOIN to this already complex query.

3
  • please put code to create tables and some sample rows. chenqui. Commented Aug 2, 2014 at 23:54
  • The stockitem table has a lot of columns Commented Aug 2, 2014 at 23:55
  • Then, put only those columns which you are interested in. Figure out a way to create a sample case. Commented Aug 2, 2014 at 23:56

1 Answer 1

1

If the column is indeed in that table, then you can use this SELECT in the CTE.

You don't need another join, you just need the name column to be part of the categoryPath CTE.

SELECT Id,
       ,Slug
       ,CategoryName 
     FROM Categories
     WHERE ParentCategoryId IS NULL
UNION ALL
SELECT Categories.Id
     ,CAST(categoryPath.Slug + '/' + categories.Slug AS NVARCHAR(150))  
     ,CategoryName
     FROM Categories

Don't forget to update the CTE definition with:

WITH categoryPath(Id,Slug,CategoryName)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.