How to find and replace content in MySQL

I messed up my SQL tables just now, luckily I did back up before I play with these things. What I was trying to do is to be neater. I don’t want a link to point at some empty location in my blog.

What I did is to do a replacement in certain fields to update blog.beconfused.com into beconfused.com or beconfused.com/blog

That really messed my tables up because my MySQL knowledge sucks. I come from a Microsoft SQL (MSSQL) background. Not that I am an expert in MSSQL, I think I got a B for that module and I remember Yong Liang got an A or probably a distinction. MSSQL is like Yong Liang’s forté.

UPDATE `NameOfTable` SET `NameOfAttribute`= replace(`NameOfAttribute`, "ReplaceFromString", "ReplaceToString")

Well, the syntax looks something like this. What it is trying to do is to UPDATE the field `NameOfAttribute` in the table `NameOfTable`. Then there is this nice little function called ‘replace‘ where you can replace any part of the string from `ReplaceFromString` to `ReplaceToString`.

An example would be:

UPDATE `wp_posts` SET `post_content` = replace(`post_content`, "http://blog.beconfused.com/archives/", "http://beconfused.com/blog/")

What this code is doing is to perform a find and replace. It targets the text “http://blog.beconfused.com/archives/” and changes it into “http://beconfused.com/blog/”. It searches in the field `post_content` under the table `wp_posts`.

What’s left is just my upgrade to WordPress 1.5. :)

4 thoughts on “How to find and replace content in MySQL

  1. Nafcom

    Yeah, I know what you mean. I have learned SQL myself, was part of my education, but never used it since 2 years. I doubt I am a good SQL coder nowadays.

  2. Mr. Dew

    Nafcom: Yeah, my girlfriend and I wishes there would be an undo feature in SQL, lol..

    Well, you just have to back up everything before you play with it I suppose.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please leave these two fields as-is: