返回"未找到" MySQL查询

时间:2017-07-20 16:26:39

标签: mysql sql

我有下表名为tbl_pet_types:

+----------+-------------+
| pet      | type        |
+----------+-------------+
| cat      | mammal      |
| dog      | mammal      |
| goldfish | fish        |
| goldfish | seacreature |
| snake    | reptile     |
+----------+-------------+

我想构建一个查找type =& chibhibian'在表中,并返回

type       pet
amphibian  NOT FOUND

因为在tbl_pet_types中找不到两栖动物

我尝试使用IF()来执行此操作:

SELECT IF(type=NULL, type, type), IF(pet=NULL, 'NOT FOUND', pet)
FROM tbl_pet_types
WHERE type='amphibian';

但查询仍然返回一个空集。如何更改查询以获得我想要的结果?

1 个答案:

答案 0 :(得分:0)

您可以尝试一下,但如果您需要搜索多种类型,可能会变得很麻烦:

SELECT 
    a.`type`,
    IF(b.`type` IS NULL, 'NOT FOUND', b.pet) as `pet`
FROM (SELECT 'amphibian' as `type`) a 
LEFT JOIN tbl_pet_types b
    ON a.`type` = b.`type`
WHERE type='amphibian';