Home > Database > Mysql Tutorial > How Can I Replace Part of a String in a MySQL Column While Updating?

How Can I Replace Part of a String in a MySQL Column While Updating?

DDD
Release: 2025-01-07 15:37:40
Original
501 people have browsed it

How Can I Replace Part of a String in a MySQL Column While Updating?

MySQL database column value partial string replacement update

MySQL provides powerful functionality that allows users to modify column values ​​by replacing specific parts of strings. This feature is particularly useful in scenarios where data needs to be updated without affecting certain elements in the string.

Suppose you have a MySQL database table with two columns: "id" and "url". The "url" column contains URLs with a specific structure, similar to:

<code>http://domain1.example/images/img1.jpg</code>
Copy after login

However, you want to modify all URLs to point to different domains while retaining the filenames. The required URL should look like this:

<code>http://domain2.example/otherfolder/img1.jpg</code>
Copy after login

To do this, you can use the following SQL query:

<code class="language-sql">UPDATE urls
SET url = REPLACE(url, 'domain1.example/images/', 'domain2.example/otherfolder/')</code>
Copy after login

The "REPLACE()" function in MySQL replaces a specified substring in a string. In this example, we instruct MySQL to replace any occurrences of the substring 'domain1.example/images/' with 'domain2.example/otherfolder/'.

By executing this query, you will successfully replace the portion of the string containing 'domain1.example/images/' with 'domain2.example/otherfolder/', effectively updating all URLs with the desired domain and retaining Original file name.

The above is the detailed content of How Can I Replace Part of a String in a MySQL Column While Updating?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template