SQL中有没有办法在部分结果返回NULL时设置默认返回值?
这是我的 SQL:
SELECT p.id, p.title, concat( u1.meta_value, ' ', u2.meta_value ) as fullname, concat( r.name, ', ', c.name ) as location
FROM modules_profiles p
LEFT JOIN moonlight_usermeta u1 ON p.user_id = u1.user_id AND u1.meta_key = 'first_name'
LEFT JOIN moonlight_usermeta u2 ON p.user_id = u2.user_id AND u2.meta_key = 'last_name'
LEFT JOIN modules_regions r ON r.id = p.region_id
LEFT JOIN modules_countries c ON c.id = p.country_id
WHERE p.certification IN ( 'certified' ) AND p.country_id IN ( 2 )
ORDER BY p.user_id ASC
有时,给定的配置文件没有设置region_id;因此,即使我们确实有国家/地区名称 (c.name),也会针对相应 user_id 的位置返回 NULL。
在这种情况下有没有办法只返回 c.name?
最佳答案
使用如下所示的COALESCE()
函数,它将返回列表中提供的第一个非NULL值
COALESCE(col_name, 'default_value')
对于您的情况,请执行
COALESCE(region_id, c.name)
我想,你是在专门谈论这部分
concat( r.name, ', ', c.name ) as location
您也可以使用CASE
表达式修改它
case when r.name is not null and c.name is not null
then concat( r.name, ', ', c.name ) else c.name end as location
关于MySQL - 找到 NULL 时设置默认返回值的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27006836/