我有三列mysql表 ID(整数) 日期(Varchar)(数据以dd-mm-yyyy表示) 日志日期(日期)(当前为空)
有没有可以获取日期并使用mysql日期格式(yyyy-mm-dd)更新Logdate的查询
答案 0 :(得分:2)
您可以使用STR_TO_DATE
函数将字符串转换为Date
值。您必须指定所提供的日期字符串的格式。在您的情况下,它将为'%d-%m-%Y'
。为了进行测试,您可以运行以下查询来检查其是否有效:
mysql> EXPLAIN Dummy;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| ID | int(11) | YES | | NULL | |
| oldDate | varchar(50) | YES | | NULL | |
| logdate | date | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM Dummy;
+------+------------+------------+
| ID | oldDate | logdate |
+------+------------+------------+
| 1 | 24-12-2019 | 2000-01-01 |
| 1 | 04-09-2017 | 2000-01-01 |
| 1 | 21-02-2019 | 2000-01-01 |
+------+------------+------------+
3 rows in set (0.00 sec)
mysql> SELECT oldDate, STR_TO_DATE(oldDate, '%d-%m-%Y') FROM Dummy;
+------------+----------------------------------+
| oldDate | STR_TO_DATE(oldDate, '%d-%m-%Y') |
+------------+----------------------------------+
| 24-12-2019 | 2019-12-24 |
| 04-09-2017 | 2017-09-04 |
| 21-02-2019 | 2019-02-21 |
+------------+----------------------------------+
3 rows in set (0.00 sec)
然后,您可以运行UPDATE
查询以更新logdate
列中的值。
mysql> UPDATE Dummy SET logdate = STR_TO_DATE(oldDate, '%d-%m-%Y');
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0
mysql> SELECT * FROM Dummy;
+------+------------+------------+
| ID | oldDate | logdate |
+------+------------+------------+
| 1 | 24-12-2019 | 2019-12-24 |
| 1 | 04-09-2017 | 2017-09-04 |
| 1 | 21-02-2019 | 2019-02-21 |
+------+------------+------------+
3 rows in set (0.00 sec)
答案 1 :(得分:1)
您可以从查询中进行手动定位。这是示例:
SELECT CONCAT_WS('-',RIGHT(date,4),MID(date,4,2),LEFT(date,2)) as Newdate FROM table;
然后,您可以按照以下方式构造更新查询:
UPDATE table SET Logdate = CONCAT_WS('-',RIGHT(date,4),MID(date,4,2),LEFT(date,2));
已编辑:
我删除了关于STR_TO_DATE
的第一条评论,因为经过测试,事实证明它如@Progman答案中所指出的那样是可用的。