简体   繁体   English

加入自参考表

[英]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)我需要查询它的结果是这样的(linq to sql 或 sql 命令)

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).我猜你错过了空值行(其中 CategoryId 为空)。 This is because in any RDBMS any comparison to NULL always returns false, even of you compare null to null.这是因为在任何 RDBMS 中,任何与 NULL 的比较总是返回 false,即使您将 null 与 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为了得到你想要的,我相信你需要一个 UNION 查询,联合的第二部分选择 CategoryId 为空的行

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) )声明@temp 表( [Id] [int] IDENTITY(1,1), [CategoryId] [int] NULL , Name varchar(20) )


insert into @temp(CategoryId, Name) values (null,'Group1'), (1,'Group2'), (1,'Group3')插入@temp(CategoryId, Name) 值 (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选择 t1.Name,t1.Id,t1.CategoryId,t2.Name 从 @temp t1 左外连接 @temp t2 on t1.CategoryId = t2.Id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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