2013-06-20 30 views
4

我必须做的一个UNION stament这样或多或少:如何在SQL Server中得到“选择”语句中的表名

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

UNION 

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

检索到的数据将是雇员或EMPLOYEES_HISTORY但不是在两个表。

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

回答

8
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一样会有两个分支没有重复。所以它可以避免一些不必要的工作在整个结果集中删除重复项。

如果有可能的分支(ES)内重复添加DISTINCT个别SELECT(S)

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] 

你也可以使用一个alias正如马丁在答案中所表明的那样。

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] 
0

可以实现Using Table Aliases

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] 
+3

你的回答实际上并未使用任何表的别名。 –