I have the following MySQL tables:
tbl_pet_owners:
+----+--------+----------+--------+--------------+
| id | name | pet | city | date_adopted |
A left join
is correct, but you need for the types
to be first:
SELECT DISTINCT types.type, owners.name, owners.city
FROM tbl_pet_types types LEFT JOIN
tbl_pet_owners owners
ON owners.pet = types.pet
WHERE types.type IN ('mammal', 'fish', 'amphibian', 'seacreature');
Because the WHERE
clause refers only to tbl_pet_types
, it does not change.
How left join
works is simple: It keeps all rows in the first table. Unmatched columns in the second become NULL
.
EDIT:
If you have a list of types that are not in tbl_pet_types
, then you need a left join
with all the values in a derived table:
SELECT DISTINCT tt.type, po.name, po.city
FROM (SELECT 'mammal' as type UNION ALL
SELECT 'fish' as type UNION ALL
SELECT 'amphibian' as type UNION ALL
SELECT 'seacreature' as type
) tt left join
tbl_pet_types pt
ON pt.type = tt.type LEFT JOIN
tbl_pet_owners po
ON po.pet = pt.pet;