Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to find missing rows between two related tables

I have two tables:

Table A

  • ID
  • ABC_ID
  • VAL

Table B

  • ID
  • ABC_ID
  • VAL

These two tables are directly related to each other through the ABC_ID column.

I want to find all the VAL column values in table A which are not present in table B for the same ABC_ID.

like image 261
Fazal Avatar asked Sep 30 '10 00:09

Fazal


People also ask

How do I find unmatched records between 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.

How get data from two related tables in SQL?

(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.


1 Answers

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS     (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL) 

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN      (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID) 

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B      ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL 

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

like image 139
Larry Lustig Avatar answered Sep 25 '22 09:09

Larry Lustig