views:

68

answers:

2

I have a MySQL InnoDB database.

I have a column my in 'article' table called url that needs to be updated.

Stored in article.url =

/blog/2010/article-name
/blog/1998/the-article-name
/blog/...

I need to change /blog/ to /news/. (E.g. now article.url = '/news/...')

What is the SQL needed to replace "/blog/" with "/news/" in the article.url column?

+4  A: 
update url
set article = replace(article, '/blog/', '/news/')
where article like '/blog/%'
RedFilter
This may give you problems if there is a `/blog/` in the middle of an article url.
ar
Was just adding the `where` clause as you typed that.
RedFilter
@ar, I don't believe so since Red Filter only put a % on the right side and not left side as well
Erik8
But that would still change /blog/foo/blog/bar to /news/foo/news/bar not /news/foo/blog/bar. You could use `set article = '/news/' + substring(article, 7)` instead, maybe also `where article like '/blog/%' and len(article) >= 7` just to be safe.
Rup
+1  A: 

If every url starts with "/blog/" and you don't want to change anything except the prefix, then you can just use substring() and concat() instead of replace():

update article
set url = concat('/news/',substring(url,7))
where url like '/blog/%';
Ike Walker
What does the "7" represent?
Erik8
@Erik8: "7" is the starting position for the substring: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring
OMG Ponies
But doesn't that assume that *all* url's in my database start with "/blog". What happens if I have in my database a url that starts with "/xyz/"?
Erik8
@Erik8: If a url starts with "/xyz/" then it won't match the where clause and therefore will not be updated, which I assume is the desired behavior.
Ike Walker