合并来自不同SQL查询的两个或多个列

时间:2013-10-03 15:20:49

标签: sql select merge

我很难弄清楚如何将两列与sql合并(我是新手)。它应该非常简单但我找不到办法。我有两个来自两个不同选择语句的结果,它们都具有相同行数,但不同列。我只是想把所有列“附加”在一起。

实施例。 这是第一个表格:

TrainerClass Table

这是第二张表:

DescriptionTranlsation

以下查询:

SELECT [t].* FROM [TrainerClass] AS [t];

或只是

SELECT * FROM [TrainerClass];

将显示此处显示的结果:

Query number 1 result

现在,第二个查询是:

SELECT [d].[Description] AS [Name] FROM [DescriptionTranslation] AS [d], [TrainerClass] AS [t] WHERE [d].[TableName] = 'TrainerClass' AND [d].[FieldName] = 'Name' AND [d].[Code] = [t].[Code] AND [d].[Language] = 'en-EN';

将导致此表:

Query number 2 result

非常直接。现在,我只想得到的是:

Final result

为什么我这么难?你会做什么来实现这一目标?提前谢谢!

3 个答案:

答案 0 :(得分:4)

SELECT [t].*,
       [d].[Description] AS [Name],
       [d2].[Description] AS [Description]
FROM   [TrainerClass] AS [t] join [DescriptionTranslation] AS [d] on [t].[Code] = [d].[Code]
       join [DescriptionTranslation] AS [d2] on [t].[Code] = [d2].[Code]
WHERE  [d].[TableName] = 'TrainerClass' AND 
       [d].[FieldName] = 'Name' AND 
       [d].[Language] = 'en-EN' AND
       [d2].[FieldName] = 'Description'

答案 1 :(得分:0)

我在你的表中有任何公共ID,你可以按照答案中的说明使用join,否​​则你可以使用union语句

答案 2 :(得分:0)

以下语句允许您将两个表一起加入其公共字段(代码) 然后你可以从任何一个表中选择你喜欢的任何东西。

希望这有帮助!

SELECT ID,Code,Name FROM DescriptionTranslation join TrainerClass      在DescriptionTranslation.Code = TrainerClass.Code