您好
我有两个选择查询,我想将它们合并到一个有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
答案 0 :(得分:6)
通常,您使用UNION
来“合并”查询。 但是,在这种特殊情况下,会导致单个列同时包含EyeColor
和HairColor
以及其他重复行。我怀疑这是您想要的。更好的方法可能是为您的联接表添加别名,以便您可以加入它两次:
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)
union
或union 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
。