开发者

How can I sequence a column within a table using SQL (MySQL)?

开发者 https://www.devze.com 2023-03-27 01:59 出处:网络
I have a list mapped using Hibernate with an index column. The table looks like this: mysql> select * from chart;

I have a list mapped using Hibernate with an index column. The table looks like this:

mysql> select * from chart;
+----+--------+------+-----------------------+
| id | report | indx | name                  |
+----+--------+------+-----------------------+
|  2 |      1 |    0 | Volume                |
|  3 |      2 |    0 | South Africa (Volume) |
|  5 |      2 |    2 | People                |
|  6 |      2 |    3 | Platforms             |
|  7 |      2 |    4 | People (Gender)       |
+----+----开发者_StackOverflow----+------+-----------------------+

As you can see chart id=4 for report=2 with indx=1 has been deleted.

I need to eliminate the gaps so all the indx values for a given report run in sequence from 0. I could write Java code to sort this out but SQL solution would be much easier to deploy.

Anyone know how to do this? I am using MySQL.


if this technique works on your version of MYSQL you can try

 SET @row := -1;
 UPDATE chart
 SET indx = @row := @row + 1
 WHERE report = 2
 ORDER BY indx

but I think better to change design.

0

精彩评论

暂无评论...
验证码 换一张
取 消