User has pets, pets may have pictures One picture may be set as mainpicture (mainpic=0 or mainpic=1)
I need to get all the pet data from the pets table and I also need the picture id where mainpic=1 or first picture or null if he has no picture in the picture table. I need to get the pet data even if it has no picture at all.
Currently I use 2 queries to get this done:
SELECT * FROM pets WHERE pets.userId=’$userId’ ORDER BY pets.created ASC LIMIT 5
…
for each result: SELECT id FROM pictures WHERE petId = ‘$petId’ ORDER BY mainpic DESC LIMIT 1
I need this optimized and in one query.
Thanks,
Hamlet
use an inner join to omit unmatched records
if you only want null in the picture related fields but want the pet info (your Q was a little unclear) then use a left join