【问题标题】:Problems in Right join in SQlSQL中右连接的问题
【发布时间】:2014-11-17 10:10:31
【问题描述】:

我有以下表格结构,我也提到了我的预期输出 请帮我查询,因为我对sql查询不太了解

表结构

表 1:员工详情

    FName      Id  
    Pratik      1     
    Praveen     3     
    Nilesh      2     

表 1:JoinigDocument

id    DocumentName
1     Leaving
2     Exp letter
3     birth cert

表 2:EmployeeJoiningDocument

EmpId  JoiningDocumentId
1        1
1        2
3        1
3        2
3        3
2        1
2        3

预期输出:

FName      Id  JoiningDocumentId  DocumentName   
Pratik      1     1                  Leaving         
Pratik      1     2                  Exp letter      
Pratik      1     null               birth cert      
Praveen     3     1                  Leaving        
Praveen     3     2                  Exp letter      
Praveen     3     3                  birth cert    
Nilesh      2     1                  Leaving       
Nilesh      2     null               Exp letter      
Nilesh      2     3                  birth cert     

【问题讨论】:

  • 请在表结构中包含表名。
  • Flag列背后的逻辑是什么?你是怎么知道哪一行有 1 和 0 的?
  • @Deepshikha 标志(自定义列 jsut 用于表示)表示 Employee 表中是否存在数据
  • @mxix 添加了表名
  • @Nilesh 您想要员工表中的所有数据?

标签: c# sql sql-server sql-server-2008


【解决方案1】:

您可以将查询编写为:

select  
       A.FName,
       A.Id,
       B.JoiningDocumentId,
       c.DocumentName
from @JoinigDocument C
cross join @EmployeeDetail A
Left join @EmployeeJoiningDocument B on B.EmployeeId = A.id and 
B.JoiningDocumentId = C.id
order by A.Id

首先交叉连接JoinigDocumentEmployeeDetail 表,这样您就可以获得员工和文档的所有可能组合,而不管员工是否拥有该加入文档。然后你需要做一个左连接来保留所有这些匹配并找到与EmployeeJoiningDocument中的有效条目对应的数据。

Demo

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 2010-12-11
相关资源
最近更新 更多