Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two SQL tables and return missing ids?

Tags:

sql

mysql

except

I have two simple tables: (here only the "id" column)

table1:

id
1
2
3
4

table2:

id
2
4

the sql query should compare the two tables for missing "id" in table2 and return: 1,3

any ideas? :) TY

like image 969
MilMike Avatar asked Nov 03 '11 15:11

MilMike


2 Answers

There are several ways to skin this cat:

SELECT    table1.ID
FROM      table1
WHERE     table1.ID NOT IN(SELECT table2.ID FROM table2)

Or you could use a left outer join:

SELECT          table1.ID
FROM            table1
LEFT OUTER JOIN table2 ON table1.ID = table2.ID
WHERE           table2.ID IS NULL
like image 61
James Hill Avatar answered Sep 19 '22 06:09

James Hill


select t1.*
from table1 t1
left outer join table2 t2 on t1.id = t2.id
where t2.id is null
like image 29
D'Arcy Rittich Avatar answered Sep 22 '22 06:09

D'Arcy Rittich