Ad

Prepand And Replace In One Query Mysql

- 1 answer

I'm explaining with an example for getting my solution. I've a user table having id, name, image fields.

Sample record should be,

id - 1
name - TestUser
image - temp/testuser.jpg (sometimes no sub-directory 'temp'. ie, image - testuser.jpg)

After user registers, I'm moving the image to a new subdirectory.

ie, moving from temp/testuser.jpg(testuser.jpg) to 1/testuser.jpg

So I need to update with the new url.

ie, I need two operations on here. Replace the sub-directory temp with 1, if no sub-directory prepend '1/' to the existing image url.

How can I manage these operations in one query? Kindly help me :)

Ad

Answer

I recommend using the following query

update users set
image = concat('new_dir/', substring(image from locate('/', image) + 1))
where id = 1
Ad
source: stackoverflow.com
Ad