简体   繁体   中英

join self-reference table

I have following self-reference table

Name    | Id |CategoryId
--------------------------------
Gruop1  | 1  |null
--------------------------------
Group2  | 2  | 1
--------------------------------
Group3  | 3  | 1
--------------------------------
Id=int AtuoNumber  
CategoryId=int nullable 

I need query that its result is like this (linq to sql or sql command)

Name   | Id | CategoryId  | CategoryName
---------------------------------------------------------
Gruop1 | 1  | null        | null
---------------------------------------------------------
Group2 | 2  | 1           | Group1
 ---------------------------------------------------------
Group3 | 3  | 1           | Group1
---------------------------------------------------------

I tried this code but it didn't work properly

SELECT *
 FROM   Category e1 
   inner join  Category e2 
   ON e1.Id = e2.CategoryId

Any idea?

SELECT e1.name,e1.id,e1.categoryid,e2.name as categoryname
 FROM   Category e1 
   left join  Category e2 
   ON e2.id = e1.CategoryId

I am guessing that you are missing the null valued rows (where CategoryId is null). This is because in any RDBMS any comparison to NULL always returns false, even of you compare null to null.

To get what you want, I believe you need a UNION query, with the second part of the union selecting rows where CategoryId is null

SELECT e1.Name , e1.Id , e1.CategoryId, e2.Name as CategoryName
FROM Category AS e1 INNER JOIN Category AS e2 ON e1.id = e2.CategoryId

union 

SELECT e1.Name , e1.Id , e1.CategoryId,null as CategoryName
FROM Category e1  where CategoryId is null

This will do the job for you.

declare @temp table ( [Id] [int] IDENTITY(1,1), [CategoryId] [int] NULL , Name varchar(20) )


insert into @temp(CategoryId, Name) values (null,'Group1'), (1,'Group2'), (1,'Group3')


select t1.Name,t1.Id,t1.CategoryId,t2.Name from @temp t1 left outer join @temp t2 on t1.CategoryId = t2.Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM