MySql,如果没有返回行返回默认值

标签 mysql sql

我有一个问题如下

SELECT cap_id FROM cap_master WHERE   
        (cap_type = 'Type1' AND cap_desc = 'CapDesc1') 
     OR (cap_type = 'Type2' AND cap_desc = 'CapDesc2')
     OR (cap_type = 'Type3' AND cap_desc = 'CapDesc3')
     OR (cap_type = 'Type4' AND cap_desc = 'CapDesc4')
order by cap_type,cap_desc

这会根据where 条件返回多行,我正在寻找的是不返回任何行的条件,我应该有一个默认值“0”。截至目前,我没有得到任何行。

例如,如果第三个条件 (cap_type = 'Type3' AND cap_desc = 'CapDesc3') 不匹配,我期望输出如下:

23
34
0  
45

我检查了给定的解决方案,例如

Return a value if no rows match

Return Default value if no row found -mysql

但似乎它们不适用于返回的多行。任何指针将不胜感激。

这是一个 Fiddle一起玩。

最佳答案

你想要一个左连接:

select coalesce(cm.cap_id, 0) as cap_id
from (select 'Type1' as cap_type, 'CapDesc1' as cap_desc union all
      select 'Type2' as cap_type, 'CapDesc2' as cap_desc union all
      select 'Type3' as cap_type, 'CapDesc3' as cap_desc union all
      select 'Type4' as cap_type, 'CapDesc4' as cap_desc
     ) c left join
     cap_master cm
     on cm.cap_type = c.cap_type and cm.cap_desc = c.cap_desc
order by c.cap_type, c.cap_desc;

如果你需要支持NULL cap_desc(这不是原问题的一部分),你可以这样做:

select coalesce(cm.cap_id, 0) as cap_id
from (
      select 'Type5' as cap_type, null as cap_desc
     ) c left join
     cap_master cm
     on cm.cap_type = c.cap_type and 
        (cm.cap_desc = c.cap_desc or cm.cap_desc is null and c.cap_desc is null)
order by c.cap_type, c.cap_desc;

Here是一个 SQL fiddle 。

关于MySql,如果没有返回行返回默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51168676/

相关文章:

php - 更改 mysql 服务器并出现 php 错误,相同的代码,相同的 mysql 版本

sql - 为什么 PostgreSQL 11 优化器拒绝使用包含列的索引的最佳计划?

mysql - 获取总消耗

Mysql2::错误:不正确的字符串值:'\xE2\x80\xA8\x09

sql - Django prefetch_related 与限制

sql - “Select * from table 1,table 2 是一个有效的查询吗?

sql - 在sql中用多个集合对记录进行分组

python - 系统错误 : The connection has been disabled

php - 如何执行以下插入,mysql

sql - 为每一行计算另一个表中的 child