Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top