Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace part of string in mysql table column

I have a wordpress installation and I've broken the mysql database. For posts the urls are listed as '.../wordpress//...' instead of '.../wordpress/...'

How in SQL can I go through every row in the table and (perhaps use a regular expression) to replace every instance of 'ss//' with 'ss/'?

like image 738
Ben Davis Avatar asked Oct 24 '13 20:10

Ben Davis


People also ask

How do I change a column value in MySQL?

To replace, use the REPLACE() MySQL function. Since you need to update the table for this, use the UPDATE() function with the SET clause.

How do I replace a character in a string in MySQL?

MySQL REPLACE() Function The REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: This function performs a case-sensitive replacement.


1 Answers

UPDATE sometable SET somefield=REPLACE(somefield,'/wordpress//','/wordpress/');

Edit

@Kevin asked me to explain this query, so here we go:

  • I assume the basic UPDATE is clear: In all rows of sometable assign a new value to somefield
  • the REPLACE() function does exactly what it says: It replaces text. In our use case we ant it to take the old value of somefield, then replace all ocurrencies of '/wordpress//' with '/wordpress/'
  • these two parts taken together mean, in all rows of sometable assign somefield the value, that results, if you replace all ocurrencies of '/wordpress//' with '/wordpress/' in the old value.
like image 118
Eugen Rieck Avatar answered Oct 22 '22 10:10

Eugen Rieck