MySQL查询(含CASE和WHERE子句)无结果时设置表头行值
问题
需要为查询结果的declare_certificate字段设置特定值:当存在匹配记录时设为'Y',无匹配记录时设为'N'。但当前查询在无匹配时无法返回结果,无法实现需求。
表结构与测试数据
create table Det_TMZF_Authorizations (id int, id_Det_TMZF int, authorization_format varchar(1)); Insert into Det_TMZF_Authorizations (id, id_Det_TMZF, authorization_format) values (1,1,'E'); Insert into Det_TMZF_Authorizations (id, id_Det_TMZF, authorization_format) values (2,2,'M');
当前查询语句
SELECT CASE dda.Authorization_Format WHEN COALESCE(sum(dda.Authorization_Format), '0') THEN 'N' ELSE 'Y' END declare_certificate, dda.Authorization_Format authorization_format FROM Det_TMZF_Authorizations dda WHERE dda.id_Det_TMZF = 3
现有正确结果(匹配时)
当查询id_Det_TMZF为1或2时,返回结果如下:
| declare_certificate | id_Det_TMZF | authorization_format |
|---|---|---|
| Y | 1 | E |
| Y | 2 | M |
期望结果(无匹配时)
当查询id_Det_TMZF为3(无匹配记录)时,需返回:
| declare_certificate | id_Det_TMZF | authorization_format |
|---|---|---|
| N | NULL | NULL |
解决方案
方法1:使用聚合函数确保返回一行
利用聚合函数在无匹配时返回0或NULL的特性,保证查询始终返回一行结果:
SELECT CASE WHEN COUNT(dda.id) > 0 THEN 'Y' ELSE 'N' END AS declare_certificate, MAX(dda.id_Det_TMZF) AS id_Det_TMZF, MAX(dda.authorization_format) AS authorization_format FROM Det_TMZF_Authorizations dda WHERE dda.id_Det_TMZF = 3;
COUNT(dda.id)统计匹配记录数,无匹配时为0,通过CASE设置declare_certificate为'N'MAX()函数在无数据时返回NULL,符合期望的字段值
方法2:使用LEFT JOIN固定返回行
先构造包含目标ID的临时数据集,再通过LEFT JOIN关联原表,确保无论是否匹配都返回一行:
WITH target_ids AS (SELECT 3 AS target_id) SELECT CASE WHEN dda.id IS NOT NULL THEN 'Y' ELSE 'N' END AS declare_certificate, dda.id_Det_TMZF, dda.authorization_format FROM target_ids ti LEFT JOIN Det_TMZF_Authorizations dda ON ti.target_id = dda.id_Det_TMZF;
target_ids临时表固定返回一行目标ID- LEFT JOIN保证即使原表无匹配,也会返回临时表的行,原表字段为NULL
- 通过判断原表的
id是否为NULL,设置declare_certificate的值
内容的提问来源于stack exchange,提问作者jonhurono
相关产品推荐
相关产品推荐

