【问题标题】:How can I sequence a column within a table using SQL (MySQL)?如何使用 SQL (MySQL) 对表中的列进行排序?
【发布时间】:2011-08-11 10:57:28
【问题描述】:

我有一个使用 Hibernate 和索引列映射的列表。表格如下所示:

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

如您所见,report=2 且 indx=1 的图表 id=4 已被删除。

我需要消除间隙,以便给定报告的所有索引值从 0 开始按顺序运行。我可以编写 Java 代码来解决这个问题,但 SQL 解决方案会更容易部署。

有人知道怎么做吗?我正在使用 MySQL。

【问题讨论】:

  • 你真的不应该依赖 id 在你的应用程序中是无缝的!

标签: mysql sql hibernate


【解决方案1】:

如果 this 技术适用于您的 MYSQL 版本,您可以尝试

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

但我认为最好改变设计。

【讨论】:

    猜你喜欢
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2016-09-30
    • 1970-01-01
    相关资源
    最近更新 更多