[英]create date in MySql from a varchar column parts
I am new to SQL. 我是SQL新手。 I imported multiple CSV file through ETL. 我通过ETL导入了多个CSV文件。 there is a date column and some dates are formatted as mm-dd-yyyy and some others as mm/dd/yyyy. 有一个日期列,某些日期格式为mm-dd-yyyy,另一些日期格式为mm / dd / yyyy。 I know how to get the individual part of day, month and year as follows. 我知道如何获取日,月和年的各个部分,如下所示。
#month
SELECT mid(My_Date,1,2) as Month_ FROM rl_transactional.mydb;
#day
SELECT mid(My_Date,4,2) as Day_ FROM rl_transactional.mydb;
#year
SELECT mid(My_Date,7,4) as Year_ FROM rl_transactional.mydb;
I want to concatenate all three components to get a date. 我想连接所有三个组件以获取日期。 When i run the query 当我运行查询
select CAST(
(SELECT mid(My_Date,7,4) FROM rl_transactional.mydb) + '-'
+ (int, SELECT mid(My_Date,1,2) FROM rl_transactional.mydb) + '-'
+ (int, SELECT mid(My_Date,4,2) FROM rl_transactional.mydb)
AS DATETIME)
It gives me error 它给我错误
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'int, SELECT mid(My_Date,1,2) FROM rl_transactional.mydb) + '-' + (int, SELECT mi' at line 1
Thanks! 谢谢!
Try this way: 尝试这种方式:
SELECT CAST(CONCAT(MID(My_Date,7,4) , '-'
, MID(My_Date,1,2) , '-'
, MID(My_Date,4,2))
AS DATETIME)
FROM rl_transactional.mydb
select CAST(CONCAT(mid(My_Date,7,4) ,'-' , mid(My_Date,1,2) , '-' ,mid(My_Date,4,2) ) AS DATETIME FROM rl_transactional.mydb
Changes to your above query. 对以上查询的更改。
NOTE: I would prefer to use STR_TO_DATE function of MySQL 注意:我希望使用MySQL的STR_TO_DATE函数
In mysql +
operator does not do string concatenation, you have to use concat() function for that or omit the operators entirely. 在mysql +
运算符中不执行字符串连接,因此必须使用concat()函数或完全省略运算符。
You are missing the cast function name just from the (int...) sections. 您仅在(int ...)部分中缺少转换功能名称。 But using the cast is superfluous if you convert it back to string anyway. 但是,无论如何将演员表转换回字符串都是多余的。
I woul use the following sql: 我将使用以下sql:
SELECT CAST(CONCAT(mid(My_Date,7,4), '-', mid(My_Date,1,2), '-', mid(My_Date,4,2)) AS DATETIME)
FROM rl_transactional.mydb
But you can use str_to_date() function instead the above. 但是您可以使用str_to_date()函数代替上面的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.