0

I have a field called slug in my table with values in this format:

"username/campaign-name"

I would like to remove the values "username/" and remain with only "campaign-name".

I tried the following but stuck on how I can dynamically replace the string "hello"? Any other alternative method is appreciated.

UPDATE `campaigns`
 SET `slug` = REPLACE(`slug`, `slug`,'hello') 
   WHERE `slug` IN (  
    SELECT `slug`
    FROM (
        SELECT `slug`
        FROM `campaigns` 
        LIMIT 1
    ) slug  
 );

1 Answer 1

1

I would suggest using substring_index():

UPDATE `campaigns`
     SET `slug` = substring_index(slug, '/', -1);

I'm not sure what the where clause is supposed to do. If you only want to change one row, use limit:

UPDATE `campaigns`
     SET `slug` = substring_index(slug, '/', -1)
     LIMIT 1;

For safety, you might want to verify the format of slug:

UPDATE `campaigns`
     SET `slug` = substring_index(slug, '/', -1)
     WHERE slug like '%/%' and slug not like '%/%/%';
Sign up to request clarification or add additional context in comments.

1 Comment

It works perfect well. And thanks for the last portion. I am able to validate and don't loop over everything. Thanks again

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.