Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find values that fail sql join on

Say I have a query such as:

SELECT *
FROM Table_1
JOIN Table_2
ON Table_1.Col_1 = Table_2.Col_1

So I have 100 records and 98 of them are equal so that query would print out 98 out of 100. How can I get SQL to print the 2 that failed to meet the join?

like image 220
chrstahl89 Avatar asked Oct 05 '11 15:10

chrstahl89


2 Answers

Use a LEFT JOIN:

SELECT *
FROM Table_1
LEFT JOIN Table_2 ON (Table_1.Col_1 = Table_2.Col_1)

The fields of Table_2 will be NULL where there was no match for the ON clause. You'll then be able to add a WHERE TABLE_2.Col_1 IS NULL to keep only records in Table_1 that didn't have a match in Table_2.

like image 81
Romain Avatar answered Sep 23 '22 01:09

Romain


An alternative to the LEFT JOIN is to use EXISTS.

SELECT * FROM Table_1
WHERE NOT EXISTS (SELECT * FROM Table_2 WHERE Col_1 = Table_1.Col_1)
like image 38
MatBailie Avatar answered Sep 24 '22 01:09

MatBailie