Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Update every second row string

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

like image 405
dcolumbus Avatar asked Sep 18 '13 22:09

dcolumbus


People also ask

How can I update part of a string in MySQL?

Use the MySQL REPLACE() function to replace a substring (i.e. words, a character, etc.) with another substring and return the changed string.

How can I update two rows at a time in SQL?

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);

Can we update multiple rows in a single update statement?

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 do you update even rows in SQL?

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.


2 Answers

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

like image 88
gerrytan Avatar answered Oct 21 '22 11:10

gerrytan


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.

like image 21
rohit hiresheddi Avatar answered Oct 21 '22 10:10

rohit hiresheddi