如何合并两个选择查询,从而得到一个表

时间:2011-04-01 14:38:39

标签: asp.net sql merge

您好 我有两个选择查询,我想将它们合并到一个有5列为Id, ClientId, Height, EyeColor, HairColor

的表中

查询是:

SELECT ClientCharacteristic.Id
     , ClientCharacteristic.ClientId
     , ClientCharacteristic.Height
     , GeneralLookup.LookupItem as EyeColor  
FROM dbo.ClientCharacteristic
  INNER JOIN dbo.GeneralLookup
    ON GeneralLookup.Id=ClientCharacteristic.glEyeColorId 



SELECT ClientCharacteristic.Id
     , ClientCharacteristic.ClientId
     , ClientCharacteristic.Height
     , GeneralLookup.LookupItem as HairColor  
FROM dbo.ClientCharacteristic
  INNER JOIN dbo.GeneralLookup
    ON GeneralLookup.Id=ClientCharacteristic.glHairColorId

5 个答案:

答案 0 :(得分:6)

通常,您使用UNION来“合并”查询。 但是,在这种特殊情况下,会导致单个列同时包含EyeColorHairColor以及其他重复行。我怀疑这是您想要的。更好的方法可能是为您的联接表添加别名,以便您可以加入它两次:

SELECT
  ClientCharacteristic.Id,
  ClientCharacteristic.ClientId, 
  ClientCharacteristic.Height,
  EyeLookup.LookupItem as EyeColor,
  HairLookup.LookupItem as HairColor
FROM
  dbo.ClientCharacteristic
  INNER JOIN dbo.GeneralLookup AS EyeLookup
    ON EyeLookup.Id=ClientCharacteristic.glEyeColorId
  INNER JOIN dbo.GeneralLookup AS HairLookup
    ON HairLookup.Id=ClientCharacteristic.glHairColorId

这里要注意的关键是AS子句中的INNER JOIN子句,它将连接表别名以用于查询的其余部分。这允许您在不同的键上多次连接同一个表,以便可以为不同的目的引用它。

答案 1 :(得分:5)

unionunion all只要列排列且类型相同(或可以隐式转换)就可以执行

遵循Davids建议并重新阅读问题 5

SELECT ClientCharacteristic.Id, 
       ClientCharacteristic.ClientId,  
       ClientCharacteristic.Height, 
       Eye.LookupItem as EyeColor
       Hair.LookupItem AS HairColor
FROM 
    dbo.ClientCharacteristic 
INNER JOIN 
    dbo.GeneralLookup Eye
    ON  Eye.Id=ClientCharacteristic.glEyeColorId     
INNER JOIN
    dbo.GeneralLookup Hair
    ON Hair.Id=ClientCharacteristic.glHairColorId 

答案 2 :(得分:1)

您可以使用UNION将两个查询合并为一个。

答案 3 :(得分:1)

SELECT ClientCharacteristic.Id, ClientCharacteristic.ClientId, ClientCharacteristic.Height, GeneralLookup.LookupItem as EyeColor, '' as HairColor    
FROM dbo.ClientCharacteristic INNER JOIN dbo.GeneralLookup ON GeneralLookup.Id=ClientCharacteristic.glEyeColorId
UNION
SELECT ClientCharacteristic.Id, ClientCharacteristic.ClientId, ClientCharacteristic.Height, '' as EyeColor, GeneralLookup.LookupItem as HairColor    
FROM dbo.ClientCharacteristic INNER JOIN dbo.GeneralLookup ON GeneralLookup.Id=ClientCharacteristic.glHairColorId

答案 4 :(得分:-1)

您可以像这样使用de UNION运算符:

SELECT ClientCharacteristic.Id, ClientCharacteristic.ClientId, ClientCharacteristic.Height, GeneralLookup.LookupItem as EyeColor
FROM dbo.ClientCharacteristic INNER JOIN dbo.GeneralLookup ON GeneralLookup.Id=ClientCharacteristic.glEyeColorId
UNION
SELECT ClientCharacteristic.Id, ClientCharacteristic.ClientId, ClientCharacteristic.Height, GeneralLookup.LookupItem as HairColor
FROM dbo.ClientCharacteristic INNER JOIN dbo.GeneralLookup ON GeneralLookup.Id=ClientCharacteristic.glHairColorId

请注意,UNION运算符会丢弃重复的元组。要在结果表中保留重复值,请使用UNION ALL