Pregunta

Not sure about the title of the question its right/wrong.

I have two tables

Category: CategoryID,CategoryName ,ParentCategoryID
ref_Product_Category: CategoryID, ProductID

I have written a query like this,

 SELECT  R.productID,
         C.ParentCategoryID,
         C.categoryName

 FROM    Category C 
         INNER JOIN ref_Product_Category R
            ON C.categoryID = R.categoryID

So it returned me 4 columns in the result, But now I want another column which will contain the ParentCategoryID's category name. I am not sure how to do it. Category table is self referencing table.

¿Fue útil?

Solución

Try with Left outer join on the table itself (so we do not lose any rows if INNER JOIN is used and no ParentCategoryID is specified):

SELECT  R.productID,
         C.ParentCategoryID,
         C.categoryName,
         ISNULL(C1.CategoryName, '') as ParentCategoryName
 FROM    Category C 
         INNER JOIN ref_Product_Category R
            ON C.categoryID = R.categoryID
         LEFT OUTER JOIN Category C1 on Category.ParentCategoryID = C1.CategoryID

Otros consejos

Try this:

 SELECT  R.productID,
         C.ParentCategoryID,
         C.categoryName,
         C.CategoryName,
         CP.CategoryName as ParentCategory
 FROM    Category C  
 INNER JOIN ref_Product_Category R ON C.categoryID = R.categoryID
 INNER JOIN Category CP ON Cp.CategoryID=C.ParentCategoryID

Try this one.

SELECT  R.productID,
         C.ParentCategoryID,
         C.categoryName, p.ParentCategoryName

 FROM    Category C 
         INNER JOIN ref_Product_Category R
            ON C.categoryID = R.categoryID INNER JOIN ParentCategory p on p.ParentCategoryID=c.ParentCategoryID
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top