Redshift执行UPDATE语句时无法向列nombregestorevento插入NULL值
问题原因
报错的核心原因是:当lu_gestor_evento中满足nombregestorevento LIKE 'karate%'的行,在lu_gestor_evento_pro中找不到对应id_gestorevento的匹配记录时,子查询会返回NULL。而lu_gestor_evento.nombregestorevento列应该带有NOT NULL约束,导致无法将NULL值写入该列。
即使两张表本身没有NULL值,只要关联匹配失败,就会触发这个报错。
解决方案
推荐以下几种修改方式,按需选择:
方式1:使用UPDATE FROM语法(最稳妥,仅更新匹配到的行)
Redshift支持UPDATE ... FROM的关联更新语法,这种方式只会处理两张表中id_gestorevento匹配的行,避免子查询返回NULL的情况:
begin; update lu_gestor_evento set nombregestorevento = a12.nombregestorevento from lu_gestor_evento_pro a12 where a12.id_gestorevento = lu_gestor_evento.id_gestorevento and lu_gestor_evento.nombregestorevento LIKE 'karate%'; commit;
方式2:用COALESCE保留原值(无匹配时不修改)
如果希望即使没有匹配记录,也保留原nombregestorevento的值而不报错,可以用COALESCE函数:
begin; update lu_gestor_evento set nombregestorevento = COALESCE( (select nombregestorevento from lu_gestor_evento_pro a12 where a12.id_gestorevento = lu_gestor_evento.id_gestorevento), lu_gestor_evento.nombregestorevento ) WHERE lu_gestor_evento.nombregestorevento LIKE 'karate%'; commit;
方式3:添加EXISTS条件(仅更新有匹配的行)
在WHERE子句中加入EXISTS判断,确保只有在lu_gestor_evento_pro中存在对应记录的行才会被更新:
begin; update lu_gestor_evento set nombregestorevento = (select nombregestorevento from lu_gestor_evento_pro a12 where a12.id_gestorevento = lu_gestor_evento.id_gestorevento) WHERE lu_gestor_evento.nombregestorevento LIKE 'karate%' AND EXISTS ( select 1 from lu_gestor_evento_pro a12 where a12.id_gestorevento = lu_gestor_evento.id_gestorevento ); commit;
内容的提问来源于stack exchange,提问作者pm1359
相关产品推荐
相关产品推荐

