如果没有找到行,则返回默认值 [英] Return Default value if no row found

查看:52
本文介绍了如果没有找到行,则返回默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建查询以从数据库中搜索多行,例如

I'm building query to search multiple rows from database like

SELECT 
  * 
FROM
  table1 
WHERE col1 = '012311' 
  OR col1 = '0123631' 
  OR col1 = '091233' 
  OR col1 = '092111' 

这里它返回前 3 个值,因为它们存在于表中,但最后一个不返回任何值,因为它不在表中.那么如果没有找到该值的行,我该如何在查询中设置我的默认值?

Here it returns first 3 values because they are present in the table but it returns nothing for last one because it's not in table. So how can I set my default value in the query if no row is found for that value?

推荐答案

有几种方法,取决于数据集.这是一种方法:

There are several approaches, which depend on the dataset. Here's one way:

SELECT *, 
IFNULL(
    ( SELECT col1 FROM table1 
        WHERE col1 IN ('012311','0123631','091233','092111') 
    ),
    'some_value'
) AS my_col1
FROM table1;

不一定要复制+粘贴,您必须根据具体情况进行调整.

Not neccessarily copy+paste, you will have to adjust for your specific case.

这篇关于如果没有找到行,则返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆