1

I have a number of rows in a selection with a sort index like

ID   text  date         sort_index
43   ABC   2013-05-28   3
93   DEF   2013-05-28   14
12   ABC   2013-05-28   103
[...]

Now I would like to renumber the sort_index from 0 to 2. The group element is date. How can I do that by using MySQL?

Bibhas Debnath
  • 14,559
  • 17
  • 68
  • 96
Thomas1703
  • 1,152
  • 5
  • 16
  • 33

2 Answers2

2

Try this, but not tested for every case yet.

UPDATE tbltest SET sort_index =
(
    SELECT COUNT(*) FROM (
        SELECT * FROM tbltest
    ) AS dup
    WHERE  dup.`date` = tbltest.`date` AND
           dup.sort_index < tbltest.sort_index
)
invisal
  • 11,075
  • 4
  • 33
  • 54
1

Check out this site.

In your case it would go like this:

mysql> SET @ordering_inc = 1;
mysql> SET @new_ordering = -1;
mysql> UPDATE YOUR_TABLE SET 
       sort_index = (@new_ordering := @new_ordering + @ordering_inc)
       WHERE date = '2013-05-28'
       ORDER BY sort_index ASC;

Not tested!

bitWorking
  • 12,485
  • 1
  • 32
  • 38