加入自引用表

时间:2015-09-06 09:09:54

标签: c# sql entity-framework

我有以下自我参考表

mode <- function(x) {
  unique_val <- unique(x)
  counts <- vector()
  for (i in 1:length(unique_val)) {
    counts[i] <- length(which(x==unique_val[i]))
  }
  position <- c(which(counts==max(counts)))
  if (mean(counts)==max(counts)) 
    mode_x <- 'Mode does not exist'
  else 
    mode_x <- unique_val[position]
  return(mode_x)
}
Name    | Id |CategoryId
--------------------------------
Gruop1  | 1  |null
--------------------------------
Group2  | 2  | 1
--------------------------------
Group3  | 3  | 1
--------------------------------

我需要查询其结果是这样的(linq to sql或sql command)

Id=int AtuoNumber  
CategoryId=int nullable 

我尝试了这段代码,但它没有正常工作

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

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

我猜你错过了空值行(其中CategoryId为null)。这是因为在任何RDBMS中,任何与NULL的比较总是返回false,即使你将null与null进行比较。

为了获得你想要的东西,我相信你需要一个UNION查询,联合的第二部分选择CategoryId为null的行

getKeyChar()

答案 2 :(得分:0)

这将为你完成这项工作。

声明@temp表 (     [Id] [int] IDENTITY(1,1),     [CategoryId] [int] NULL,     名称varchar(20) )

插入@temp(CategoryId,Name) 值 (NULL,&#39;组1&#39), (1,&#39;组2&#39), (1,&#39;组3&#39)

选择t1.Name,t1.Id,t1.CategoryId,t2.Name 来自@temp t1 左外连接@temp t2在t1.CategoryId = t2.Id

相关问题