1

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?

3 Answers 3

4
update url
set article = replace(article, '/blog/', '/news/')
where article like '/blog/%'
Sign up to request clarification or add additional context in comments.

4 Comments

This may give you problems if there is a /blog/ in the middle of an article url.
Was just adding the where clause as you typed that.
@ar, I don't believe so since Red Filter only put a % on the right side and not left side as well
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.
1

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/%';

3 Comments

@Erik8: "7" is the starting position for the substring: dev.mysql.com/doc/refman/5.0/en/…
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: 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.
0

I recently wanted to replace a string within MySQL on the fly, but the field could contain 2 items. So I wrapped a REPLACE() within a REPLACE(), such as:

REPLACE(REPLACE(field_name, “what we are looking for”, “replace first instance”), 
       “something else we are looking for”, “replace second instance”)

This is the syntax I used to detect a boolean value:

REPLACE(REPLACE(field, 1, “Yes”), 0, “No”)

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.