Hi
I'm looking to optimize my SQL.
My database schema is:
HOMES
- home_id
- address
- city
- state
- zip
- primary_photo_group_id
HOME_PHOTOS
- photo_id (primary key)
- home_id (home primary key)
- photo_group_id (a photo group is the same image, resize from thumbnail to large size)
- home_photo_type_id (the size of the image be it a thumbnail or a large size)
- photo_url_dir (the filesystem location where the photo is stored)
Problem
It's very possible that a 'home' does not have a photo associated with the home. In that case, the primary_photo_group_id
= 0. Otherwise,
primary_photo_group_id` equals the group_id of the photo to use as the primary photo.
Slow SQL (b/c of UNION)
SELECT homes.home_id,
address,
city,
state,
zip,
photo_id,
photo_url_dir
FROM homes, home_photos
WHERE homes.home_id = home_photos.home_id
AND primary_photo_group_id = home_photo_group_id
AND home_photo_type_id = 2
UNION
SELECT homes.home_id,
address,
city,
state,
zip,
null,
null
FROM homes
WHERE primary_photo_group_id = 0
What I would like to do
I would like to get rid of the UNION since I'm having to search back over the entire table 2x. How can I get rid of the UNION since I need to check for the case where primary_photo_group_id = 0 and if it's not equal to 0, then query the home_photos
table
Here is the pseudo code that needs to happen
SELECT homes.home_id,
address,
city,
state,
zip,
photo_id, (include only if primary_photo_group_id != 0)
photo_url_dir (include only if primary_photo_group_id != 0)
FROM homes,
home_photos (include only if primary_photo_group_id != 0)
WHERE
primary_photo_group_id = 0
ELSE
homes.home_id = home_photos.home_id
AND primary_photo_group_id = home_photo_group_id
AND home_photo_type_id = 2