我有一张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());
}
2条答案
按热度按时间rsl1atfo1#
这是一把小提琴:http://sqlfiddle.com/#!9/34699f/1号楼
r6l8ljro2#
如果不通过删除该表中的行来中断任何内容,请将其全部移动到临时表中,截断当前表,然后设置
id
要自动递增,请执行以下操作: