6

我不得不或多或少地做出这样的UNION表态:

select [table_name], name, address
from Employees
where [my_condition]

UNION

select [table_name], name, address
from Employees_history
where [my_condition]

检索到的数据将在Employees 或Employees_history 中,但不在两个表中。

我需要知道数据来自哪个表。

4

4 回答 4

12
SELECT 'Employees' AS [table_name],
       name,
       address
FROM   Employees
WHERE  [my_condition]
UNION ALL
SELECT 'Employees_history' AS [table_name],
       name,
       address
FROM   Employees_history
WHERE  [my_condition] 

我使用UNION ALL而不是UNION因为两个分支之间没有重复。因此它可以避免一些不必要的工作,删除整个结果集中的重复项。

如果分支中可能存在重复,请添加DISTINCTSELECT个人

于 2013-06-20T12:02:07.697 回答
1

您可以附加一个新字段,如下所示:

select [table_name], name, address, 'Employees'
from Employees
where [my_condition]

UNION

select [table_name], name, address, 'History'
from Employees_history
where [my_condition]

您也可以使用aliasMartin 在他的回答中显示的那样。

于 2013-06-20T12:02:16.190 回答
0

你不能做这样的事情:

select 'Employees' as table_name, name, address
from Employees
where [my_condition]

UNION

select 'Employees_history' as table_name, name, address
from Employees_history
where [my_condition]
于 2013-06-20T12:03:00.977 回答
0

可以使用表别名来实现

SELECT 'Employees' AS [table_name],
       name,
       address
FROM   Employees
WHERE  [my_condition]

UNION

SELECT 'History' AS [table_name],
       name,
       address
FROM   Employees_history
WHERE  [my_condition] 
于 2013-06-20T12:07:06.670 回答