如何从MySQL查询的字符串中提取数值? [英] How do you extract a numerical value from a string in a MySQL query?

查看:191
本文介绍了如何从MySQL查询的字符串中提取数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列的表:price(int)和price_display(varchar).

I have a table with two columns: price (int) and price_display (varchar).

price是实际的数字价格,例如"9990"

price is the actual numerical price, e.g. "9990"

price_display是视觉表示,例如"$ 9.99"或"9.99Fr"

price_display is the visual representation, e.g. "$9.99" or "9.99Fr"

我已经能够通过regexp确认两列是否匹配:

I've been able to confirm the two columns match via regexp:

price_display不是regexp 格式(价格/1000,2)

price_display not regexp format(price/1000, 2)

但是在不匹配的情况下,我想从price_display列中提取值并将其设置为price列,所有这些都在update语句的上下文中.我还没办法弄清楚.

But in the case of a mismatch, I want to extract the value from the price_display column and set it into the price column, all within the context of an update statement. I've not been able to figure out how.

谢谢.

推荐答案

此函数仅从字符串中返回数字0-9,这可以很好地解决您的问题,而不管前缀或后缀是什么你有.

This function does the job of only returning the digits 0-9 from the string, which does the job nicely to solve your issue, regardless of what prefixes or postfixes you have.

http://www.artfulsoftware.com/infotree/query.php?& bw = 1280#815

此处复制以供参考:

SET GLOBAL log_bin_trust_function_creators=1;
DROP FUNCTION IF EXISTS digits;
DELIMITER |
CREATE FUNCTION digits( str CHAR(32) ) RETURNS CHAR(32)
BEGIN
  DECLARE i, len SMALLINT DEFAULT 1;
  DECLARE ret CHAR(32) DEFAULT '';
  DECLARE c CHAR(1);

  IF str IS NULL
  THEN 
    RETURN "";
  END IF;

  SET len = CHAR_LENGTH( str );
  REPEAT
    BEGIN
      SET c = MID( str, i, 1 );
      IF c BETWEEN '0' AND '9' THEN 
        SET ret=CONCAT(ret,c);
      END IF;
      SET i = i + 1;
    END;
  UNTIL i > len END REPEAT;
  RETURN ret;
END |
DELIMITER ;

SELECT digits('$10.00Fr'); 
#returns 1000

这篇关于如何从MySQL查询的字符串中提取数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆