简体   繁体   中英

How to compare between two tables?

this is my query

select * from table as a 
where a.* not in 
(select * from table B)

I want to have the difference beteween two tables there is a specific function?

By definition, EXCEPT returns distinct rows by comparing the results of two queries.

EXCEPT returns distinct rows from the left input query that aren't output by the right input query.

The basic rules are:

  • The number and the order of the columns must be the same in all queries.
  • The data types must be compatible.
 CREATE TABLE MyTableA (ColA int, ColB int) CREATE TABLE MyTableB (ColA int, ColB int) INSERT INTO MyTableA (ColA, ColB) VALUES (15,1),(10,1),(2,1),(2,1),(16,1),(2,2),(3,3),(3,3) INSERT INTO MyTableB (ColA, ColB) VALUES (1,1),(1,1),(1,1),(2,2),(4,5),(1,1),(4,5)

GO

 SELECT * FROM MyTableA EXCEPT SELECT * FROM MyTableB Select * from MyTableA as a where not exists (Select 1 from MyTableB as b where a.ColA = b.ColA and a.ColB = b.ColB) GO
 ColA | ColB ---: |  ---: 2 |  1 3 |  3 10 |  1 15 |  1 16 |  1 ColA |  ColB ---: |  ---: 15 |  1 10 |  1 2 |  1 2 |  1 16 |  1 3 |  3 3 |  3 

db<>fiddle here

You can see that using EXCEPT generated duplicate entries, if you want to get rid of that you may need an ID column to both tables and update your query to:

Select *
from MyTableA as a where not exists (Select 1 from MyTableB as b
where a.ColA = b.ColA and a.ColB = b.ColB and a.ID <> b.ID)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM