H2 - 用索引号(0,1,2,3,...)更新每一行

时间:2016-09-02 21:41:34

标签: java sql h2

我在H2 db中有一个表,它存储了一些有序列表:

CREATE TABLE IF NOT EXISTS items 
(
  f_id      INTEGER NOT NULL PRIMARY KEY,
  f_name    VARCHAR(255) NOT NULL,
  f_index   INTEGER NOT NULL UNIQUE
)


|f_id|f_name|f_index|
|1   |A     |1      |
|2   |C     |3      |
|3   |B     |4      |
|4   |D     |2      |

当我删除项目'D'时,我需要将C的索引更新为2,将B的索引更新为3.

当我这么做时,我会发疯的。我不想简单地

UPDATE items SET f_index = f_index-1 WHERE f_index > ?

因为我害怕我的桌子可能包含间隙(由未知原因引起),所以我找了类似的东西

SqlRowSet rowSet = jdbcTemplate.queryForRowSet("SELECT f_name FROM items ORDER BY f_index");
int i = 0;
while (rowSet.next()) {
    String name = rowSet.getString("f_name");
    jdbcTemplate.update("UPDATE items SET f_index = ? WHERE f_name= ?", i++, name);   
}

但更优雅。

有没有办法用H2来实现我的需求?

1 个答案:

答案 0 :(得分:1)

如果您只想使用h2,则可以使用以下语句

with f as (
      select f.folderrsn, fpi.processrsn, fpi.infocode,
             fpi.infovalue, fp.enddate
      from folderprocessinfo fpi join
           folderprocess fp
           on fp.processrsn = fpi.processrsn join
           folder f
           on f.folderrsn = fp.folderrsn
      where fpi.infocode in (51437, 51438, 51439) and
            trunc(f.issuedate) > '01-JAN-16' and
            fpi.infovalue is not null
     )
select f.*
from (select f.*,
             row_number() over (partition by processid, type order by enddate desc) as seqnum
      from f
     ) f
where seqnum = 1
order by enddate asc;