如何解析mySQL文本字段中的特定数字

时间:2015-01-26 16:03:20

标签: mysql phpmyadmin

我有一个表格列,每个字段中都有一堆文字。每个字段中都有一个特定的句子,它保持一致(实际价格除外),表示:

"价格是15,350美元。"

我想从每个字段中解析出美元数字并将其放入自己的专栏中。

实现这一目标的SQL语句是什么?

2 个答案:

答案 0 :(得分:1)

mysql> select replace(replace(mid("The price is $15,350.", 15), ",", ""), ".", "");
+----------------------------------------------------------------------+
| replace(replace(mid("The price is $15,350.", 15), ",", ""), ".", "") |
+----------------------------------------------------------------------+
| 15350                                                                |
+----------------------------------------------------------------------+

答案 1 :(得分:1)

试试这个:(另请查看SQL Fiddle of the solution

SELECT 
  REPLACE(
    SUBSTRING(
      SUBSTRING( myval,
      LOCATE('The price is $', myval) + 15,
      LENGTH(myval) - LOCATE('The price is $', myval)
    ), 1,
      LOCATE('.',
        SUBSTRING( myval,
          LOCATE('The price is $', myval) + 15,
          LENGTH(myval) - LOCATE('The price is $', myval))
       ) 
    ), ',', '') as Result

FROM tbl

原始答案(保留,因为它涵盖了一些基本的解析概念,并通知了最后提交的解决方案):

如果事情是一致的,那么一系列简单的REPLACE函数可以用空字符串删除原始值 。例如:

SELECT your_column AS original_value,
REPLACE(REPLACE(your_column, 'The price is $', ''), '$', '') AS parsed_value
FROM your_table 

输出:

original_value           parsed_value
The price is $15,350.    15,350.

你可以包装一个额外的REPLACE调用来删除逗号',',如下所示:

SELECT your_column AS original_value,
REPLACE(
    REPLACE(
        REPLACE(your_column, 
            'The price is $', ''), '$', ''), ',', '') AS parsed_value
FROM your_table 

新产品:

original_value           parsed_value
The price is $15,350.    15350.

编辑 - 解决“价格是......”块附近的其他文字:

SELECT your_column AS original_value,
SUBSTRING('The price is $',
    LOCATE ('The price is $', your_column)
REPLACE(
    REPLACE(
        REPLACE(your_column, 
            'The price is $', ''), '$', ''), ',', '')
,

AS parsed_value     来自your_table

结果值15350现在应该可以轻松地转换为小数,并且结果会附加CAST(xxxxx AS DECIMAL(10,2))