如何从SQL Server中的表中获取不匹配的数据

时间:2018-11-22 22:41:11

标签: sql sql-server tsql sql-server-2008 sql-server-2005

我试图通过比较MS SQL Server中的两个表从两个表中获取不匹配的数据,并获取不匹配的数据

例如

表1:

id |  user  | password | token | 
1  | Andres | 121212   | e12A1 |  
2  | Louie  | 131312   | e12A2 |
3  | Marcus | 141312   | e22A2 |
4  | Mark   | 141312   | e22A2 |

表2:

id |  user   | password | token | 
1  | Andres  | 121212   | e12A1 |  
2  | Louie   | 131312   | e12A2 |
6  | Grace   | 151312   | e13A2 |
7  | Sophia  | 159312   | e14A2 |

预期输出:

id |  user   | password | token |
3  | Marcus  | 141312   | e22A2 |
4  | Mark    | 141312   | e22A2 |
6  | Grace   | 151312   | e13A2 |
7  | Sophia  | 159312   | e14A2 |

解决该问题的任何查询都将有所帮助

2 个答案:

答案 0 :(得分:2)

您可以使用EXCEPTUNION比较两个表:

SELECT * FROM 
    (
        SELECT * FROM #Temp1 
        EXCEPT
        SELECT * FROM #Temp2
    ) A
UNION 
SELECT * FROM 
    (
        SELECT * FROM #Temp2
        EXCEPT
        SELECT * FROM #Temp1 
    ) B

或者您可以使用NOT EXISTS()

SELECT * FROM #Temp1 T1 WHERE NOT EXISTS (SELECT 1 FROM #Temp2 T2 WHERE T1.id=T2.id)
UNION
SELECT * FROM #Temp2 T2 WHERE NOT EXISTS (SELECT 1 FROM #Temp1 T1 WHERE T1.id=T2.id)

答案 1 :(得分:0)

您也可以使用WINDOW FUNCTION来满足您的要求。有关WINDOW FUNCTION的更多详细信息,可以参考它。 https://docs.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-2017

create table [Table 1]
(id int ,
 [user] varchar(10),
 password varchar(10),
 token varchar(10))

 create table [Table 2]
(id int ,
 [user] varchar(10),
 password varchar(10),
 token varchar(10))

insert into [Table 1] values 
(1,'Andres','121212','e12A1'),
(2,'Louie','131312','e12A2'),
(3,'Marcus','141312','e22A2'),
(4,'Mark','141312','e22A2')

insert into [Table 2] values 
(1,'Andres','121212','e12A1'),
(2,'Louie','131312','e12A2'),
(6,'Grace','151312','e13A2'),
(7,'Sophia','159312','e14A2')

;with cte1 as (
select * from [Table 1]
union all 
select * from [Table 2]
)
,cte2 as (
select *,
count(*)over(partition by id,[user],password,token ) as ct  
from cte1 )
select * from cte2 where ct=1
/*
id          user       password   token      ct
----------- ---------- ---------- ---------- -----------
3           Marcus     141312     e22A2      1
4           Mark       141312     e22A2      1
6           Grace      151312     e13A2      1
7           Sophia     159312     e14A2      1
*/