Transact SQL基于外键返回数据

时间:2014-07-07 18:15:14

标签: sql-server tsql

让表A有两列,每列都是其他表的外键,可以存储关键数据。需要根据这些列撤回关键数据,例如名称。可以对每个表执行左连接,但是这将包含许多空值,因此要避免这种情况。外键不使用空值,因为每个值都可能存在一个键 - 但我们不使用该方式,因此一个字段的值为另一个字段。

示例:

A

Index  App   Ten
----------------
  1     123    0
  2     124    0
  3      0     125
  4      0     126

App

Index  LName
---------------
 123     Jones
 124     Smith

Ten

Index   Lname
---------------
 125      Doe
 126      Williams

连接这些表以根据索引选择表的正确方法是什么(如果为零则忽略)并返回所需的数据而不使用左连接和空值?

期望的输出:

Index  App   Ten  Lname
------------------------------
  1     123    0    Jones
  2     124    0    Smith
  3      0     125  Doe
  4      0     126  Williams

2 个答案:

答案 0 :(得分:3)

Select A.Ind, A.App, A.Ten, coalesce(ap.LName,t.LName) 
from A 
LEFT JOIN App ap on ap.Ind = A.App 
LEFT JOIN Ten t on A.Ten = t.Ind

Coalesce将选择第一个值,如果第一个值为null,则将选择第二个值

答案 1 :(得分:1)

select a.[index], a.App, 0 as [Ten], App.Lname 
  from a 
  join App 
    on a.App = App.[Index] 
 where a.App <> 0
intersect 
select a.[index], 0 as [App], a.Ten, Ten.Lname 
  from a 
  join Ten
    on a.Ten = Ten.[Index] 
 where a.Ten <> 0
 order by 1

从App获取值,然后将它们与十个相交 &LT;&GT;忽略0条线索

相关问题