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

MySQL导入CSV时CASE WHEN语句失效,所有行返回2的排查求助

问题原因与修正方案

我一眼就看出问题出在哪了——你在CASE语句里直接用了status,但这个status是你要写入的表字段,不是CSV文件里的原始值!

当LOAD DATA执行时,它会先把CSV里的status值写入表的status字段,然后你在SET子句里又试图用这个表字段做判断,这相当于用已经写入的值去覆盖自己,逻辑完全乱了。而且因为某种原因(比如表的status字段默认值是'C',或者赋值逻辑的优先级问题),所有行都匹配了第一个WHEN status='C'的条件,所以全变成了2。

修正后的完整语句

解决方法很简单:把CSV里的原始状态值先暂存到一个用户变量(比如@status),然后用这个变量做CASE判断就好了,另外CASE外面的SELECT是多余的,直接写CASE表达式就行:

load data local infile 'C:\\Scripts\\Storagefile.csv' 
into table infra.storage 
fields terminated by ',' enclosed by '"' 
lines terminated by '\r\n' 
ignore 1 rows 
(@status, gasday, gasinstorage, percent_full, net_change, injection, withdrawal, workingstorage, injection_cap, withdrawal_cap, @dummy) 
set status = (case when @status = 'C' then 2 when @status = 'E' then 1 when @status = 'N' then 0 end), 
entity = 'EU', 
gasinstorage = gasinstorage * 3.142142, 
net_change = net_change * 3.142142, 
injection = injection * 3.142142, 
withdrawal = withdrawal * 3.142142, 
workingstorage = workingstorage * 3.142142, 
injection_cap = injection_cap * 3.142142, 
withdrawal_cap = withdrawal_cap * 3.142142, 
reportdate = current_timestamp()

额外提醒

如果你的CSV里可能存在'C'/'E'/'N'之外的状态值,建议给CASE加个ELSE分支,比如ELSE NULL或者你指定的默认值,避免出现意外的NULL值或者不符合预期的结果。

内容的提问来源于stack exchange,提问作者Vincent Turner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:24:50