在字段中使用反斜杠查找并替换字符串的特定部分

时间:2014-02-20 09:28:41

标签: mysql serialization

例如,这是myTable

| i | data    |
+---+---------+
| 1 | d\one   |
| 2 | d\two   |
| 3 | d\three |

但我想将其更改为:

| i | data  |
+---+-------+
| 1 | one   |
| 2 | two   |
| 3 | three |

我知道如何在字段中找到带反斜杠的字符串的特定部分:

SELECT * FROM myTable WHERE data LIKE 'd%\%'

我知道如何找到&将字段替换为值,只有此查询不起作用:

UPDATE myTable SET data=REPLACE(data,'d\','') WHERE data LIKE 'd%\%'

3 个答案:

答案 0 :(得分:2)

你需要逃避反斜杠

UPDATE myTable 
SET data = REPLACE(data,'d\\','') 
WHERE data INSTR('d\\') = 1

SQLFiddle demo

答案 1 :(得分:0)

尝试这个..

UPDATE myTable SET `data`=REPLACE(`data`,'d\','');

答案 2 :(得分:0)

我希望你应该在\\\中使用三次斜杠\\而不是双斜杠Like Clause。正如我所尝试的那样,我无法从使用\\

中选择数据
SELECT * FROM mytable WHERE data LIKE 'd\\%';
Empty set (0.00 sec)

mysql> SELECT * FROM mytable WHERE data LIKE 'd\\\%';
+---------+
| data    |
+---------+
| d\one   |
| d\two   |
| d\three |
+---------+
3 rows in set (0.00 sec)

mysql> SELECT REPLACE(data,'d\\','') FROM mytable WHERE data LIKE 'd\\\%';
+------------------------+
| REPLACE(data,'d\\','') |
+------------------------+
| one                    |
| two                    |
| three                  |
+------------------------+
3 rows in set (0.00 sec)

mysql> UPDATE mytable SET data =  REPLACE(data,'d\\','') WHERE data LIKE 'd\\\%';
Query OK, 3 rows affected (0.06 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> SELECT * FROM mytable;
+-------+
| data  |
+-------+
| one   |
| two   |
| three |
+-------+
3 rows in set (0.00 sec)