我不得不或多或少地做出这样的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 中,但不在两个表中。
我需要知道数据来自哪个表。
我不得不或多或少地做出这样的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 中,但不在两个表中。
我需要知道数据来自哪个表。
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
因为两个分支之间没有重复。因此它可以避免一些不必要的工作,删除整个结果集中的重复项。
如果分支中可能存在重复,请添加DISTINCT
到SELECT
个人
您可以附加一个新字段,如下所示:
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
Martin 在他的回答中显示的那样。
你不能做这样的事情:
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]
可以使用表别名来实现
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]