user2557039
user2557039

Reputation: 71

join two tables and select records only if NOT in table 2

I would like to join two tables and only print records from table 1 where the rec_number is NOT in table 2.

table 1
name        rec_number
john smith   123
Bob jonson   345
etc

Table 2 
Bob jonson   345
etc

What is the query in php that would do this so the query only gives me John smith, not bob jonson. is it:

    $query = "select * from table1
    left join rec_number on table1.rec_number = table2.rec_number";
    $result=mysql_query($query);

Thank you.

Upvotes: 0

Views: 84

Answers (2)

dognose
dognose

Reputation: 20909

Beside the left join mentioned by Abhik, you could also use a subselect:

SELECT * FROM table1 WHERE table1.name NOT IN (SELECT name FROM table2);

Upvotes: 0

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44874

You can use this query

select 
t1.*
from table1 t1
left join table2 t2 
on t2.rec_number = t1.rec_number
where t2.rec_number IS NULL

Upvotes: 2

Related Questions