2

我已将日期保存为字符串,例如:Fri Apr 04 15:58:43 BST 2014 年份总是在末尾,我想进行查询以获取年份小于特定年份的记录,例如 2012。这可能吗?如何?是否可以从 mysql 解决此问题?即,将日期从字符串转换为日期?

4

2 回答 2

4

您可以使用 MySQLSTR_TO_DATE()函数将这些值转换为 MySQL 日期:

mysql> select str_to_date('Fri Apr 04 15:58:43 BST 2014','%a %b %d %H:%i:%S BST %Y');
+------------------------------------------------------------------------+
| str_to_date('Fri Apr 04 15:58:43 BST 2014','%a %b %d %H:%i:%S BST %Y') |
+------------------------------------------------------------------------+
| 2014-04-04 15:58:43                                                    |
+------------------------------------------------------------------------+
1 row in set (0.00 sec)

这是一个粗略的示例,使用您的示例字符串来说明一个查询以返回日期在 2012 年之前的所有行。它将需要全表扫描,因此速度不会很快,但它说明了您需要做什么的基本概念:

select *
from your_table
where str_to_date(your_column,'%a %b %d %H:%i:%S BST %Y') < '2012-01-01'
于 2012-07-24T21:37:20.123 回答
1

这是一个基线查询

SELECT REVERSE(LEFT(REVERSE('Fri Apr 04 15:58:43 BST 2014'),4));

在这里执行

mysql> SELECT REVERSE(LEFT(REVERSE('Fri Apr 04 15:58:43 BST 2014'),4));
+----------------------------------------------------------+
| REVERSE(LEFT(REVERSE('Fri Apr 04 15:58:43 BST 2014'),4)) |
+----------------------------------------------------------+
| 2014                                                     |
+----------------------------------------------------------+
1 row in set (0.00 sec)

mysql>

天哪,我在想什么???我实际上是在解码它

SET @datestring = 'Fri Apr 04 15:58:43 BST 2014';
SELECT CONCAT(YYYY,'-',MM,'-',DD,' ',HHMMSS) dt FROM
(SELECT REVERSE(LEFT(REVERSE(@datestring),4)) as YYYY,
SUBSTR(FLOOR((LOCATE(LEFT(SUBSTR(@datestring,5),3),'JanFebMarAprMayJunJulAugSepOctNovDec')+2)/3)+100,2) MM,
SUBSTR(@datestring,9,2) DD,
SUBSTR(@datestring,12,8) HHMMSS) A;

我的解码工作

mysql> SET @datestring = 'Fri Apr 04 15:58:43 BST 2014';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT CONCAT(YYYY,'-',MM,'-',DD,' ',HHMMSS) dt FROM
    -> (SELECT REVERSE(LEFT(REVERSE(@datestring),4)) as YYYY,
    -> SUBSTR(FLOOR((LOCATE(LEFT(SUBSTR(@datestring,5),3),'JanFebMarAprMayJunJulAugSepOctNovDec')+2)/3)+100,2) MM,
    -> SUBSTR(@datestring,9,2) DD,
    -> SUBSTR(@datestring,12,8) HHMMSS) A
    -> ;
+---------------------+
| dt                  |
+---------------------+
| 2014-04-04 15:58:43 |
+---------------------+
1 row in set (0.00 sec)

mysql>
于 2012-07-24T21:32:27.443 回答