java—更新一行一行的mysql后必须对一组数据进行排序

pgvzfuti  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(291)

我有一张table table1 在没有主键的mysql数据库中:

+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| id      | int(11)     | YES  |     | NULL    |       |
| value   | varchar(25) | YES  |     | NULL    |       |
| my_date | date        | YES  | MUL | NULL    |       |
| my_time | time        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+

在按我的日期和时间值对表排序之后,是否可以从给定的值开始更新id值?
例如,从这组值

+------+------------+----------+
| id   | my_date    | my_time  |
+------+------------+----------+
|    0 | 2018-03-01 | 09:02:00 |
|    0 | 2018-03-01 | 09:01:00 |
|    0 | 2018-03-01 | 09:00:00 |
+------+------------+----------+

我想获得

+------+------------+----------+
| id   | my_date    | my_time  |
+------+------------+----------+
|  100 | 2018-03-01 | 09:00:00 |
|  101 | 2018-03-01 | 09:01:00 |
|  102 | 2018-03-01 | 09:02:00 |
+------+------------+----------+

我试过这样的方法但没有成功:

try {
    int idFromToStart = 100; 
    String query = "SELECT IFNULL(id, 0) FROM table1 WHERE my_date > '2018-02-28' order by my_date, my_time";
    preparedStatement =con.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);            
    ResultSet rs = preparedStatement.executeQuery(query);
    System.out.println("query " + query);            
    if (rs.next()) {
        rs.updateLong(1, idFromToStart);
        System.out.println("rs.getLong(1)) "+rs.getLong(1)+ " idFromToStart "+idFromToStart);
        idFromToStart++;
    }
} catch (SQLException ex) {
    System.out.println("Error db " + ex.getMessage() + " " + ex.toString());
}
rsl1atfo

rsl1atfo1#

SET @rownum = 99;
UPDATE tbl1
SET tbl1.id = @rownum:=@rownum+1
ORDER BY my_time

这是一把小提琴:http://sqlfiddle.com/#!9/34699f/1号楼

r6l8ljro

r6l8ljro2#

如果不通过删除该表中的行来中断任何内容,请将其全部移动到临时表中,截断当前表,然后设置 id 要自动递增,请执行以下操作:

INSERT INTO table1 (`value`, my_date, my_time)
SELECT `value`, my_date, my_time
FROM myTmpTable
ORDER BY my_date, my_time ASC;

相关问题