I have two table: Vehicles(Id, VIN) and Images(Id, VehicleId, Name, Default). I need to select the vehicles VIN and its default picture to display in a table. The problem I am having is that if a default picture is not set I still would like to select an image to display if it exists. If no images exist the vehicle information obviously must also still display. Here is what I have so far:
SELECT
Vehicles.Id, Vehicles.VIN, Images.Name AS Image,
(SELECT COUNT(*) FROM Images WHERE VehicleId = Vehicles.Id) AS ImageCount
FROM
Vehicles
LEFT JOIN
Images ON Images.VehicleId = Vehicles.Id
WHERE
Images.Default = 1
This statement will display vehicles which have a default image but will not display anything if no default is set.
To describe my problem better here is some test data:
VEHICLES:
ID VIN
1 12341234123412341
2 23452345234523452
3 34534534534534534
IMAGES:
ID VEHICLEID NAME DEFAULT
1 1 a 1
2 1 b 0
3 2 c 0
4 2 d 0
Even though vehicle 2 has no default I want it to select an image to display. Also vehicle 3 has no images at all but I still need it to show up in the table with no image. Vehicle 1 will display its default image because it is set. I hope this clears things up.