You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL中为不存在的记录返回默认值?

实现不存在的记录返回默认值的方法

要达成你想要的效果,核心思路是先构造包含所有目标查询值的数据集,再与原表做左连接——这样所有目标值都会保留,原表中无匹配的记录对应字段会是NULL,最后用函数将NULL替换为你指定的默认文本。

标准SQL写法(适配多数数据库)

WITH target_values AS (
    SELECT 1 AS col1 UNION ALL
    SELECT 2 UNION ALL
    SELECT 3
)
SELECT 
    tv.col1,
    COALESCE(t.fruit, 'sorry this value does not exist in the table') AS fruit
FROM target_values tv
LEFT JOIN tables t ON tv.col1 = t.col1;

MySQL 8.0+/MariaDB 简洁写法

MySQL支持直接用VALUES构造临时数据集:

SELECT 
    tv.col1,
    IFNULL(t.fruit, 'sorry this value does not exist in the table') AS fruit
FROM (VALUES (1), (2), (3)) AS tv(col1)
LEFT JOIN tables t ON tv.col1 = t.col1;

低版本MySQL(不支持VALUES构造表)写法

用UNION ALL手动拼接目标值:

SELECT 
    tv.col1,
    IFNULL(t.fruit, 'sorry this value does not exist in the table') AS fruit
FROM (
    SELECT 1 AS col1 UNION ALL
    SELECT 2 UNION ALL
    SELECT 3
) tv
LEFT JOIN tables t ON tv.col1 = t.col1;

关键说明

  • 自定义的临时数据集(如target_values)确保所有要查询的col1值都能出现在结果中;
  • LEFT JOIN会保留临时表的全部记录,原表匹配到的取对应fruit值,无匹配则fruit为NULL;
  • COALESCE(标准SQL)或IFNULL(MySQL专属)负责将NULL替换为预设的默认文本。

执行后会得到你期望的结果:

col1fruit
1apples
3bananas
2sorry this value does not exist in the table

内容的提问来源于stack exchange,提问作者h ca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 12:13:11