mysql的几个函数

缘由是数据库里的fax是由“区号+空格+号码”组成的,但是现在需要去掉空格。下图:update fax
先说简单点的方法:

UPDATE customer_copy set fax=REPLACE(fax,' ','')   where fax REGEXP '^[0-9]+[[:space:]][0-9]+';

细说一下:
REPLACE(fax,’ ‘,”),是替换空格
REGEXP ,是mysql里的正则
‘^[0-9]+[[:space:]][0-9]+’,是匹配 以至少有一个数字开头,后面有个空格,后面再跟着至少一个数字的记录。
再来一个另类的:

UPDATE customer_copy set fax= concat(substring_index(fax,' ',1), substring_index(fax,' ',-1))  where fax REGEXP '^[0-9]+[[:space:]][0-9]+';

这里用到了两个函数:concat(),substring_index()
concat(p1,p2,p3) 是拼接函数。把他的所有参数连接起来,结果就是p1p2p3
substring_index(str,delim,count) 返回字符串str中,第count个分隔符delim之前的子串.
SUBSTRING_INDEX(‘www.mysql.com’, ‘.’, 2); 返回第2个.之前的字串,也就是www.mysql
SUBSTRING_INDEX(‘www.mysql.com’, ‘.’, -2); 返回mysql.com
解释一下,如果count是负数,就从右边开始计数和截取。
substring_index(fax,’ ‘,1), 返回区号部分,substring_index(fax,’ ‘,-1), 返回空格后的号码,再用concat一组合,也就是去掉空格后的号码了。

Leave a comment

3 Comments.

  1. 请问一下楼主 文章里面代码高亮显示 用的什么插件?

  2. 淡水河边

    @intkids
    是coolcode插件

  3. UGG boots for sale

    看了你的博客名字,感觉相当的亲切,因为我家也是在淡水河边的

Leave a Reply


[ Ctrl + Enter ]

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word