我在2个不同的数据库中有2个表,并且服务器是相同的。
表1:
ID Name Address date
=======================================
1 abc 123 xyz 1-1-2018
2 efg 456 pqr 1-20-2018
表2:
ID Name Address Date
-----------------------------------
1 abc xxxx 1-1-2017
2 xjy yyyy 1-20-2017
我希望两个表的结果都显示如下:
ID Name Address Date
-------------------------------------
1 abc 123 xyz 1-1-2018 This is from table 1
1 abc xxxx 1-1-2017 This is from table 2
如何在两个表中仅显示id来显示我的结果?
答案 0 :(得分:2)
您可以使用union all
:
select t.*
from ( (select t1.ID, t1.Name, t1.Address, t1.date
from table1 t1
where exists (select 1 from table2 t2 where t2.id = t1.id)
) union all
(select t2.ID, t2.Name, t2.Address, t2.date
from table2 t2
where exists (select 1 from table1 t1 where t2.id = t1.id)
)
) t;
答案 1 :(得分:0)
您可以使用UNION:
select id, [name], address, [date], cast('This is from table 1' as varchar(100))
from table1 where id in (select id from table2)
union
select id, [name], address, [date], cast('This is from table 2' as varchar(100))
from table2 where id in (select id from table1);