문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top