Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Query help to get non matching records from two tables

I am trying to get non matching records from 2 tables

For ex

TableA
 ID           Account
 1               Acc1
 2               Acc2
 3               Acc3

 TableB
 Opp          Accountid
 Opp1            1
 Opp2            2
 Opp3            4

I need to know which accountid is present in TableB but not in TableA. It would be wonderful if someone could provide this query.

Required record would be Opp3 of tableB

Thanks

Prady

like image 293
Prady Avatar asked Apr 30 '11 07:04

Prady


People also ask

How do I get only non-matching records from two tables in SQL?

The second way to find non-matching records between tables is to use NOT in conjunction with the IN operator. The IN operator allows you to specify multiple values in a WHERE clause, much like a string of ORs chained together.

How do I find unmatched rows in two tables?

Use the Find Unmatched Query Wizard to compare two tables One the Create tab, in the Queries group, click Query Wizard. In the New Query dialog box, double-click Find Unmatched Query Wizard. On the first page of the wizard, select the table that has unmatched records, and then click Next.


4 Answers

SELECT B.Accountid 
  FROM TableB AS B 
  LEFT 
  JOIN TableA AS A 
    ON A.ID = B.Accountid 
 WHERE A.ID IS NULL;

LEFT JOIN means it takes all the rows from the first table - if there are no matches on the first join condition, the result table columns for table B will be null - that's why it works.

like image 70
David Fells Avatar answered Nov 15 '22 17:11

David Fells


create table #one (id int,acc nvarchar(25))
insert into #one (id , acc) values(1,'one') 
insert into #one (id , acc) values(2,'two') 
insert into #one (id , acc) values(3,'three') 

create table #two (acct nvarchar(25),ids int)
insert into #two (acct,ids) values('one',1) 
insert into #two (acct,ids) values('two',3) 
insert into #two (acct,ids) values('four',4) 

select ids from #two EXCEPT select id from #one 

drop table #one 
drop table #two 

test this one

like image 31
Nighil Avatar answered Nov 15 '22 19:11

Nighil


SELECT B.Accountid
FROM TableB AS B 
LEFT JOIN TableA AS A ON A.ID = B.Accountid 
WHERE A.ID IS NULL
like image 35
Kumaran NJ Avatar answered Nov 15 '22 17:11

Kumaran NJ


try this

(select * from t1
except 
select * from t2)

union

(select * from t2
except 
select * from t1)

thinking that you have the same number of columns in both tables

query mentioned above select ids from #two EXCEPT select id from #one will give u non matching rows from only #two . it will neglect that of #one

like image 20
Kuntady Nithesh Avatar answered Nov 15 '22 17:11

Kuntady Nithesh