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

时间:2018-07-04 08:03:14

标签: 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

4 个答案:

答案 0 :(得分:1)

我将使用IFNULL来做您想要的事情。它未经测试,因为您没有提供最少的数据集来在以下位置运行查询:

SELECT IFNULL( (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) ,'0');

Here,您可以找到有关IFNULL的更多详细信息

答案 1 :(得分:1)

您想要一个left join

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提琴。

答案 2 :(得分:1)

我能够找出解决方案。不知道这是否会极大地影响效率,我想我一次最多将有20个条件。让我知道是否还有其他选择。

SELECT ifnull((SELECT cap_id FROM cap_master WHERE cap_type = 'Type4' AND 
cap_desc = 'CapDesc4' ),0) as cap_id
union all
SELECT ifnull((SELECT cap_id FROM cap_master WHERE cap_type = 'Type7' AND 
cap_desc = 'CapDesc7' ),0) as cap_id
union all
SELECT ifnull((SELECT cap_id FROM cap_master WHERE cap_type = 'Type3' AND 
cap_desc = 'CapDesc3' ),0) as cap_id
union all
SELECT ifnull((SELECT cap_id FROM cap_master WHERE cap_type = 'Type6' AND 
cap_desc = 'CapDesc6' ),0) as cap_id

答案 3 :(得分:0)

尝试CASE功能:)您可以指定应显示的内容和位置

https://www.w3schools.com/sql/func_mysql_case.asp