tags:

views:

61

answers:

3

I have a typical Persons table and an Orders table defined in such a way that I can do JOIN query as the following to return Orders for all Persons.

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.id=Orders.Person_id

The question is, how do I write a statement that would return all Persons with NO Orders?

I'm using mysql.

Thank all in advance.

+8  A: 

You may want to use LEFT JOIN and IS NULL:

SELECT     Persons.LastName, Persons.FirstName
FROM       Persons
LEFT JOIN  Orders ON Persons.id = Orders.Person_id
WHERE      Orders.Person_id IS NULL;

The result of a left join always contains all records of the "left" table (Persons), even if the join-condition does not find any matching record in the "right" table (Orders). When there is no match, the columns of the "right" table will NULL in the result set.

Daniel Vassallo
+2  A: 

This should work... theres more than one way to do it.

select * from persons where person.id not in (select person_id from orders)
David
A: 

Just for completeness, here is the not exists version:

select * from persons p 
where not exists
(select null from orders o where o.person_id = p.id)
Mark Bannister
All three answers work just just as I wished. Thanks to all of you.
timeon