0

I know how to replace a string using a query like:

UPDATE  `postmeta` SET  `meta_value` = REPLACE(`meta_value`, 'old_string', 'replacement')

What I want to do is for Mysql to choose a random string from a list of strings, sort of like this:

UPDATE  `postmeta` SET  `meta_value` = REPLACE(`meta_value`, 'old_string', RAND(['replacement','replacement2','replacement3']))

OR

I would like for it to cycle through the list instead of choose them randomly... eg: Replace the first record with 'replacement', second record with 'replacement2', fourth record with 'replacement'...

Is this sort of query possible?

4 Answers 4

2

You can use MySQL's ELT function. ELT() returns the N th element of a list of strings: str1 if N = 1, str2 if N = 2, and so on:

UPDATE `postmeta` 
SET `meta_value` = REPLACE(`meta_value`, 'old_string', 
  ELT(1 + RAND() * 3, 'replacement', 'replacement2', 'replacement3'))
Sign up to request clarification or add additional context in comments.

2 Comments

Alright this is great but while writing the question, I had another idea. Say the query will update 200 rows. Is there any way to get the number of the row being currently updated? I would be able to cycle through the list instead of randomly selecting using (current_iteration % length_of_list +1) in ELT.
That's trickier. I would suggest reading this article for a few pointers.
1

You could use rand() and a case expression:

update `postmeta` 
set `meta_value` = replace(
    `meta_value`, 
    'old_string',
    case floor(1 + rand() * 2) 
        when 1 then 'replacement'
        when 2 then 'replacement2'
        when 3 then 'replacement3'
    end
);

floor(1 + rand() * 2) generates a random value between 1 and 3 (see the documentation for more details).

Comments

1

Use can use the elt() function and rand():

UPDATE postmeta
    SET meta_value = REPLACE(meta_value, 'old_string', 
                             ELT(FLOOR(RAND() * 3 + 1, 'replacement', 'replacement2', 'replacement3')
                            );

If you don't want to actually replace part of the string, but want to assign the whole string, then I think you want:

UPDATE postmeta
    SET meta_value = ELT(FLOOR(RAND() * 3 + 1, 'replacement', 'replacement2', 'replacement3')
    WHERE meta_value = 'old_string';

Comments

0
//you could use ran() for example of my own:
CREATE TABLE RandomFirstNames (
    id SMALLINT UNSIGNED AUTO_INCREMENT,
    first_name VARCHAR(...),
    PRIMARY KEY(id) )
SELECT first_name FROM FirstNames ORDER BY RAND();

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.