简体   繁体   中英

Find and replace a specific part of a string with a backslash in a field

For example this is myTable :

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

But I want to change it to:

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

I know how to find a specific part of a string with a backslash in a field:

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

I know how to find & replace a field a value, only this query won't work:

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

You need to escape the backslash

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

SQLFiddle demo

试试这个......

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

I hope you should put triple slash \\\\\\ instead of double slash \\\\ in Like Clause . As I have tried I am unable to pick data from using \\\\

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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