views:

462

answers:

4

For example, I have a pet table and a lost pets table. I want to get all of the pets that are NOT lost with 1 join and no sub-selects. Is that possible? A typical join only returns results that are in both tables.

+4  A: 

You're describing an OUTER JOIN as compared to a standard INNER JOIN. Google or check your documentation - I'm sure you'll find lots of examples. :)

SELECT * FROM pets AS p
LEFT OUTER JOIN lost-pets AS lp
ON p.name = lp.name
WHERE lp.id IS NULL

le dorfier
+1  A: 

It is possible, yes, say :

SELECT *
FROM pets LEFT OUTER JOIN pets-lost ON pets.id = pets-lost.id
WHERE pets-lost.id IS NULL;
mat
A: 

Why not do where not exists (select * from Lost ...)? Its a sub-select, but I don't see why thats a problem.

eulerfx
one problem is that e.g. old versions of mysql don't support subselects.
le dorfier
one other problem, is that subselects are much more slow than joins.
mat
one additional problem is that the question asked how to do it without sub selects
Dave L.
@mat: "subselects are much more slow than joins" not always true. You need to actually measure. Some subselects are optimized into joins.
S.Lott
The better the query optimizer, the less it matters. However, some are dumb indeed.
Zan Lynx
+2  A: 
SELECT PETS.NAME
FROM PETS
   LEFT OUTER JOIN LOST_PETS
     ON PETS.PET_ID = LOST_PETS.PET_ID
WHERE LOST_PETS.PET_ID IS NULL;
Scott Bevington