Including values NOT FOUND in MySQL query results

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

I have the following MySQL tables:

tbl_pet_owners:

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


        
3条回答
  •  猫巷女王i
    2021-01-27 14:45

    Does MySQL STILL not have CTEs? They make life so much easier.

    Regardless, to get 'NOT FOUND', use coalesce() in your SELECT.

    SELECT DISTINCT p.petType
        , coalesce(po.name,'NOT FOUND') AS name
        , coalesce(po.city,'NOT FOUND') AS city
    FROM (
        SELECT 'mammal' AS petType UNION ALL
        SELECT 'fish' UNION ALL
        SELECT 'amphibian' UNION ALL
        SELECT 'seacreature'
    ) p
    LEFT OUTER JOIN (  
        SELECT tpo.name, tpo.city, pt.type AS petType
        FROM tbl_pet_owners tpo
        LEFT OUTER JOIN tbl_pet_types tpt ON tpo.pet = tpt.pet
    ) po ON p.petType = po.petType
    

    I don't have a MySQL machine to test this on, but something like this should give you what you're looking for.

提交回复
热议问题