mysql - SELECT 和 INSERT 语句中 str_to_date 的不同行为
问题描述
我有与这个问题相同的问题 - MySQL Unable to insert WHERE STR_TO_DATE IS NULL。
我想将日期从一个数据库迁移到另一个数据库。原始数据库中的日期存储为 varchars,并不总是有效 - 例如,有时有一个像“nb”或其他字符串这样的值,有时它们是空的。在 SELECT 语句中使用 str_to_date() 可以正常工作 - 如果提供的字符串与提供的格式不匹配,则返回 null。这是我想要的行为,但在 INSERT 语句中。不幸的是,在尝试这样做时,我收到以下错误:
SQL Error (1411): Incorrect datetime value: 'n.b.' for function str_to_date
你有什么建议可以避免这种行为吗?
如果这很重要,我正在使用 MariaDB。
编辑 1:这是我的 INSERT 语句:
insert into person
(id, firstname, lastname, date_of_birth, place_of_birth, gender, old_id)
select
vm.person_id,
IFNULL(wv.vorname, '') as firstname,
IFNULL(wv.NAME, '') as lastname,
STR_TO_DATE(wv.geburtsdatum, '%e.%c.%Y') as date_of_birth,
null as place_of_birth,
case
when wv.anrede = 'Herr' then 'm'
when wv.anrede = 'Frau' then 'w'
else 'x'
end as gender,
vm.old_id
from b.helper_table vm
join a.orig_table wv
on vm.old_id = wv.id;
解决方案
它适用于正则表达式 - 感谢@MatBailie。
insert into person
(id, firstname, lastname, date_of_birth, place_of_birth, gender, old_id)
select
vm.person_id,
IFNULL(wv.vorname, '') as firstname,
IFNULL(wv.name, '') as lastname,
case
when wv.geburtsdatum REGEXP '^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$' then
str_to_date(wv.geburtsdatum, '%e.%c.%Y')
end as date_of_birth,
null as place_of_birth,
case
when wv.anrede = 'Herr' then 'm'
when wv.anrede = 'Frau' then 'w'
else 'x'
end as gender,
vm.old_id
from b.helper_table vm
join a.orig_table wv
on vm.old_id = wv.id;
推荐阅读
- go - 查找项目中未使用的 protobuf 字段
- angular - 数据更新后,Angular 9 chartJs 不更新视图
- unity3d - 如何在动画中保持相同的持续时间的同时将一个统一动画换成另一个?
- deep-learning - 仍然对 model.train() 感到困惑
- c# - Ajax POST 适用于 [FromForm] 但不适用于 [FromBody]
- kotlin - 从数据类foreach方法制作列表
- ios - 在IOS中将UISearchbar背景颜色设置为白色
- c++ - 找到一对圆锥曲线的内公切线
- visual-studio-code - 直接使用 Linux 在 samba 中编辑文件?
- python - 为什么输入字段中的 request.form 不起作用?