从同一服务器上的两个数据库db1和db2带来唯一数据

时间:2018-07-19 05:00:52

标签: sql sql-server sql-server-2008

我在同一服务器上有两个数据库名称db1和db2,我需要一个SQL查询来获取唯一数据。下面是数据库和表名

db1

Table_db1

EmailID           Name     Mobile
raj@gmail.com     raj      7207542655
kumar@gmail.com   kumar    111111111

db2

Table_db2

 EmailID          Name     Mobile
raj@gmail.com     raj      7207542655
rohan@gmail.com   rohan    5555555555

raj@gmail.com从表中删除了重复项,输出应为

raj@gmail.com     raj      7207542655
kumar@gmail.com   kumar    111111111
rohan@gmail.com   rohan    5555555555

我需要基于Table_db1和Table_db2的EmailID从db1和db2获得唯一数据

从Table_db1和Table_db2中获取单个EmailID数据

2 个答案:

答案 0 :(得分:0)

你可以试试吗

 SELECT distinct te1.Emailid, (select top 1 [name] from [db1].dbo._Table_1 as te11 where te11.emailid = te1.emailid) as [Name]
  FROM [db1].dbo._Table_1 as te1
 WHERE EXISTS  (
               SELECT emailId 
                 FROM [db2].dbo._Table_1 as te2
                WHERE te1.emailid = te2.emailid
              )  

UNION

SELECT distinct te1.Emailid, (select top 1 [name] from [db1].dbo._Table_1 as te11 where te11.emailid = te1.emailid) as [Name]
  FROM [db1].dbo._Table_1 as te1
 WHERE not EXISTS  (
               SELECT emailId 
                 FROM [db2].dbo._Table_1 as te2
                WHERE te1.emailid = te2.emailid
              )  


UNION

SELECT distinct te2.Emailid, (select top 1 [name] from [db2].dbo._Table_1 as te22 where te22.emailid = te2.emailid) as [Name]
  FROM [db2].dbo._Table_1 as te2
 WHERE not EXISTS  (
               SELECT emailId 
                 FROM  [db1].dbo._Table_1 as te1
                WHERE te1.emailid = te2.emailid
              )  

答案 1 :(得分:0)

您的行完全相同。只需使用:retest if not exist "C:\Users\Desktop\Label\Revised 150718\test2.csv" ( goto :NoFile ) else ( DEL "C:\Users\Desktop\Label\Revised 150718\test2.csv" Echo Deleting file goto :retest ) :NoFile

:retest
if not exist "C:\Users\Desktop\Label\Revised 150718\test2.csv" (
timeout 10
goto :retest
) else (
    DEL "C:\Users\Desktop\Label\Revised 150718\test2.csv"
    Echo Deleting file
    goto :retest
)

如果其他列可以不同并且表中没有重复项,则:

union