Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4153143
  • 博文数量: 240
  • 博客积分: 11504
  • 博客等级: 上将
  • 技术积分: 4277
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-28 14:24
文章分类

全部博文(240)

分类:

2008-02-12 16:13:41

今天看到PGSQL的函数这一节。
POSTGRESQL 相比MYSQL多了好多实用的函数。
1、正则替换。
t_girl=# create table t_regexp(id serial not null,username char(20) not null);
NOTICE: CREATE TABLE will create implicit sequence "t_regexp_id_seq" for serial column "t_regexp.id"
CREATE TABLE
Time: 6.148 ms
t_girl=# insert into t_regexp(username) values ('Shit,shit'),('i I i I you');
INSERT 0 2
Time: 2.893 ms
t_girl=# select * from t_regexp;
 id | username
----+----------------------

  1 | Shit,shit
  2 | i I i I you
(2 rows)

Time: 0.296 ms
t_girl=# update t_regexp set username = regexp_replace(username,'[Ss]','a','g');
UPDATE 2
Time: 1.139 ms
t_girl=# select * from t_regexp;
 id | username
----+----------------------

  1 | ahit,ahit
  2 | i I i I you
(2 rows)

Time: 0.271 ms
t_girl=# update t_regexp set username = regexp_replace(username,'a(..)',E'S\\1P','g');
UPDATE 2
Time: 2.090 ms
t_girl=# select * from t_regexp;
 id | username
----+----------------------

  1 | ShiPt,ShiPt
  2 | i I i I you
(2 rows)

Time: 0.289 ms
t_girl=#
可惜MYSQL的REPLACE函数只能简单的替换字符串。
以往碰到这种正则替换,先把数据导出到文本,然后再外部用正则替换掉,再导入到数据库中。
2、字符分割。
获取分割指定的字符串部分,这个在MYSQL中也是只能用循环解决。
Time: 0.306 ms
t_girl=# select split_part('now,year,month',',',2);
 split_part
------------

 year
(1 row)

Time: 0.328 ms
t_girl=# select split_part('now,year,month',',',3);
 split_part
------------

 month
(1 row)

Time: 0.253 ms
t_girl=#
这个在MYSQL中只能通过写一个循环来判断。
至于双方的效率暂时还没有测试。
3、顺序替换字符,这个也是MYSQL中没有的。

t_girl=# select translate('now,year,month','mo','ab');
   translate
----------------

 nbw,year,abnth
(1 row)

Time: 0.309 ms
4、截取符合正则的子串。
t_girl=# SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{1,3})');
 substring
-----------

 1
(1 row)

Time: 0.246 ms
t_girl=# SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{2,3})');
 substring
-----------

 12
(1 row)
5、等待更新。。。
阅读(4015) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

aaxron2008-03-25 09:41:34

8错,期待更多好文