I need to be able to update every even
(2, 4, 6, etc) row string within the image
column ... the name will end with an extension .png
and I want to insert some text before the .jpg
So from MyImage.png
to MyImage-Small.png
Then I need to be able to do the same for every odd
(1, 3, 5, etc) row
Use the MySQL REPLACE() function to replace a substring (i.e. words, a character, etc.) with another substring and return the changed string.
There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);
Column values on multiple rows can be updated in a single UPDATE statement if the condition specified in WHERE clause matches multiple rows. In this case, the SET clause will be applied to all the matched rows.
How can I get even and odd records in SQL? Write a subquery with an ORDER BY clause. Along with the data columns, select the pseudocolumn rownum with an alias, say rn. In the outer query, reference the alias rn and use the mod function to get odd rows or even rows.
Assuming the table has a numeric primary key column id
, you can do this for even rows:
update mytable set picture = replace(picture, '.png', '-Small.png') where id % 2 = 0;
Similarly just change the predicate to id % 2 = 1
for odd rows
If the table has no numeric key which is a continuous sequence then we can still achieve selective updates for odd and even rows by using following update.
UPDATE mytable o
INNER JOIN
(SELECT id, @row :=@row +1,mod(@row,2) AS num
FROM mytable, (SELECT @row := 0) r)AS t
ON o.id = t.id -- any indexed field which is unique for the table
SET o.image =
CASE num
WHEN 0 THEN 'even_row'
WHEN 1 THEN 'odd_row'
END;
All this query is doing is generating the sequence for the table then joining it with the original table so we update odd and even rows separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With