Including values NOT FOUND in MySQL query results

后端 未结 3 864
星月不相逢
星月不相逢 2021-01-27 14:17

I have the following MySQL tables:

tbl_pet_owners:

+----+--------+----------+--------+--------------+
| id | name   | pet      | city   | date_adopted |
         


        
3条回答
  •  别那么骄傲
    2021-01-27 15:00

    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;
    

提交回复
热议问题