LEFT JOIN将不明确的列放入SQL语句的一列中?

时间:2014-03-19 16:11:49

标签: sql sql-server

是否可以LEFT JOIN两个具有相同性质的列,即将t2.Namet3.Name加入到T-SQL语句中的单个列(dataproperty)Name中?

SELECT t1.ID,
       t1.RowID,
       t2.name, 
       t3.Name 
  FROM MasterTable T1 
       LEFT OUTER JOIN RightTable1 T2 
            ON T1.RowID = T2.ID 
       LEFT OUTER JOIN RightTable2 T3 
            ON T1.RowID = T3.ID 
 WHERE t1.ID= " & ID & ";

...或者我是否必须将表格加载到单独的数据集中并以编程方式(对于每个...下一个)将它们连接到新数据集中?

此致

Libor的

2 个答案:

答案 0 :(得分:2)

这取决于你所说的帽子"加入" - 这里有几种可能性:

如果一个为空而另一个为空,则使用ISNULL

SELECT DISTINCT 
       t1.ID,
       t1.RowID,
       ISNULL(t2.name, t3.Name) Name
FROM MasterTable T1 
LEFT OUTER JOIN RightTable1 T2 on T1.RowID = T2.ID 
LEFT OUTER JOIN RightTable2 T3 on T1.RowID = T3.ID 

如果你想连接它们:

SELECT DISTINCT 
       t1.ID,
       t1.RowID,
       t2.name + t3.Name Name
FROM MasterTable T1 
LEFT OUTER JOIN RightTable1 T2 on T1.RowID = T2.ID 
LEFT OUTER JOIN RightTable2 T3 on T1.RowID = T3.ID 

如果你想要两行(一个UNION):

SELECT DISTINCT 
       t1.ID,
       t1.RowID,
       t2.Name
FROM MasterTable T1 
LEFT OUTER JOIN RightTable1 T2 on T1.RowID = T2.ID 
UNION ALL
SELECT DISTINCT 
       t1.ID,
       t1.RowID,
       t3.Name
FROM MasterTable T1 
LEFT OUTER JOIN RightTable2 T3 on T1.RowID = T3.ID 

请注意,DISTINCT是必要的,因为除非您可以关联T2和T3,否则您基本上在T2和T3之间进行交叉连接(笛卡尔积),因此您需要消除所创建的重复项。

答案 1 :(得分:0)

SELECT t1.ID,
       t1.RowID,
       t2.name + t3.Name AS JoinedName
  FROM MasterTable T1 
       LEFT OUTER JOIN RightTable1 T2 
            ON T1.RowID = T2.ID 
       LEFT OUTER JOIN RightTable2 T3 
            ON T1.RowID = T3.ID 
 WHERE t1.ID= " & ID & ";