查询SQL Server中三个表的数据

时间:2015-07-27 06:37:27

标签: sql sql-server select sql-server-2005

我有3个名为tbl_mondaytbl_tuesdaytbl_wednesday的表,其中包含以下数据:

tbl_monday

id    empid   Plan
---------------------
1     6       Mon_27
2     6       Mon_27
3     6       Mon_27

tbl_tuesday

id    empid   Plan
--------------------
1     6       Tue_28
2     6       Tue_28
3     6       Tue_28     

tbl_wenesday

id  empid     Plan
------------------
1     6       Wed_29
2     6       Wed_29
3     6       Wed_29

有没有简单的方法来获得这样的结果?

empid    Plan
----------------------
6       Mon_27
6       Tue_28
6       Wed_29

2 个答案:

答案 0 :(得分:5)

您可以在三个表之间使用union进行查询,这将提供所有查询的唯一结果:

SELECT empid, [plan] FROM tbl_monday
UNION
SELECT empid, [plan] FROM tbl_tuesday
UNION
SELECT empid, [plan] FROM tbl_wednesday

<强> SQLFiddle

答案 1 :(得分:1)

简单就是使用union all

select *
from
(
    select top 1 empid, plan
    from tbl_monday
    order by id
) m

union all

select *
from
(
    select top 1 empid, plan
    from tbl_tuesday
    order by id
) t

union all

select *
from
(
    select top 1 empid, plan
    from tbl_Wednesday 
    order by id
) w

虽然您似乎应该重新考虑数据库设计。