【问题标题】:Extract date from string in MySQL从 MySQL 中的字符串中提取日期
【发布时间】:2014-08-11 20:40:47
【问题描述】:

我的字符串数据列格式如下:

Katy Perry Tickets - Staples Center. 09/19/2014 7:30 PM. 209 11

Atlanta Braves Tickets vs Miami Marlins Tickets - Turner Field. 08/31/2014 5:10 PM. 411L 2

我需要从每个字段中提取日期值,常见的格式是从右边看第一个句号,直到下一个句号。日期总是在这两者之间。

日期左侧的文本中偶尔会出现句号,因此我们无法相信。

我怎样才能得到那个特定的子字符串? SQL 大师,需要您的建议......

谢谢。

【问题讨论】:

  • 不要在 mysql 中这样做。 mysql 正则表达式只能进行匹配。他们不能捕捉。你被基本的字符串操作困住了,即使是那些在 sql 中也可能非常痛苦的操作。使用正则表达式仅提取其中包含日期的记录,然后使用客户端代码进行实际提取。
  • 你试过SUBSTR(读取SUBSTRING)功能吗?你试过什么?
  • 下面的Cheruvian使用Substring_Index得到了完美的解决方案。

标签: mysql string substring


【解决方案1】:

尝试使用Substring_Index

Select  Substring_Index(Substring_Index( txt, ".",  -2), ".", 1)
From    Tablename

【讨论】:

    【解决方案2】:

    您可以使用 PREG functions for mysql ,我已经安装了 UDF 功能,我得到了这个:

    1- 创建和插入示例数据:

    create table your_table (
        txt_col text
    );
    
    insert into your_table values  
    ('Katy Perry Tickets - Staples Center. 09/19/2014 7:30 PM. 209 11'),
    ('Atlanta Braves Tickets vs Miami Marlins Tickets - Turner Field. 08/31/2014 5:10 PM. 411L 2');
    

    2- 使用日期模式测试 PREG_CAPTURE 函数:

    mysql> SELECT PREG_CAPTURE(
               '/([0-9]+\\/[0-9]+\\/[0-9]+)\\s[0-9]+:[0-9]+\\s[a-z]+/i' , 
               txt_col, 0  ) as date_captured, 
        txt_col from your_table;
    +--------------------+--------------------------------------------------------------------------------------------+
    | date_captured      | txt_col                                                                                    |
    +--------------------+--------------------------------------------------------------------------------------------+
    | 09/19/2014 7:30 PM | Katy Perry Tickets - Staples Center. 09/19/2014 7:30 PM. 209 11                            |
    | 08/31/2014 5:10 PM | Atlanta Braves Tickets vs Miami Marlins Tickets - Turner Field. 08/31/2014 5:10 PM. 411L 2 |
    +--------------------+--------------------------------------------------------------------------------------------+
    2 rows in set (0.00 sec)
    

    date_captured 列是提取的文本。

    【讨论】:

      猜你喜欢
      • 2016-06-24
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多