简体   繁体   English

MySQL Regex替换查询

[英]MySQL Regex Replace Query

I have a field with this value: 我有一个具有此值的字段:

TEST:ATEST:TESTA

And I want to replace "TEST" with "NEW", I have tried this query: 我想将“ TEST”替换为“ NEW”,我尝试过以下查询:

UPDATE `table` SET `field` = REPLACE(`field`, 'TEST', 'NEW') WHERE `field` REGEXP 'TEST';

The result was: 结果是:

NEW:ANEW:NEWA

Q: How could I do the replacement query so the result would be like this: 问:如何执行替换查询,所以结果将如下所示:

NEW:ATEST:TESTA

It is a bit of a pain, but you can do it this way: 这有点痛苦,但是您可以这样操作:

UPDATE `table`
    SET field = substr(REPLACE(concat(':', field, ':'), ':TEST:', ':NEW:'),
                       2, length(REPLACE(concat(':', field, ':'), ':TEST:', ':NEW:')) - 2)
    WHERE concat(':', field, ':') LIKE '%:TEST:%';

I prefer LIKE to REGEXP because there is the hope of being able to use an index. 我希望LIKE REGEXP因为希望能够使用索引。 That is not a possibility in this case, but there is the hope. 在这种情况下这是不可能的,但是有希望。

This is delimiting the values with colons at the beginning and the end, and only replacing fully delimited values. 这是在开头和结尾用冒号分隔值,并且仅替换完全分隔的值。 The trick is to then remove the additional colons. 诀窍是然后删除其他冒号。

You can try http://sqlfiddle.com/#!9/4e66b/3 您可以尝试http://sqlfiddle.com/#!9/4e66b/3

so the update query is (if table name = table1, field name = field1, and there is unique column id): 因此更新查询为(如果表名称= table1,字段名称= field1,并且有唯一的列ID):

UPDATE `table1` 
INNER JOIN
  (SELECT id, 
    @set_idx:=FIND_IN_SET('TEST',REPLACE(field1,':',',')),
    @set_size:=LENGTH(field1)-LENGTH(REPLACE(field1,':',''))+1,
    CASE 
      WHEN @set_idx=1 THEN CONCAT('NEW',SUBSTRING(field1, 4))
      WHEN @set_idx>1 THEN CONCAT(SUBSTRING_INDEX(field1, ':',@set_idx-1),':NEW', IF(@set_size>@set_idx,CONCAT(':',SUBSTRING_INDEX(field1, ':',-(@set_size-@set_idx))),''))
    END as new
  FROM table1
  WHERE `field1` REGEXP '(^TEST$)|(^TEST:)|(:TEST$)|(:TEST:)'
   ) t
ON t.id = table1.id
SET table1.field1 = t.new;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM