如何在 h2 中使用一个查询删除重复项

How to remove duplicates with one query in h2

我需要删除特定字段 (instrument_id) 的重复记录,仅保留 id 的第一条记录。

使用 MySQL 示例,此查询如下所示:

DELETE t1 FROM instrument_bit_detail t1, instrument_bit_detail t2
WHERE t1.id > t2.id AND
t1.instrument_id = t2.instrument_id;

创建 table 的示例:

CREATE TABLE `instrument_bit_detail` (
  `id` bigint(20) NOT NULL,
  `instrument_id` bigint(20) NOT NULL,
  `modification_time` datetime DEFAULT NULL
)

但是使用H2hsqldb数据库时无法执行此查询,提示语法错误。

是否有一些方法可以完成类似于上述查询的重复删除,但可以在 h2hsqldb 上完成数据库?

像这样的简单查询应该可以解决问题:

DELETE FROM instrument_bit_detail t1
WHERE t1.id > (SELECT MIN(t2.id) FROM instrument_bit_detail t2 WHERE t1.instrument_id = t2.instrument_id )

编辑: 由于您似乎有一些语法错误,这是我在 h2 网络控制台(版本 1.4.200)上测试过的内容。

创建Table

CREATE TABLE instrument_bit_detail (
  id bigint(20) NOT NULL,
  instrument_id bigint(20) NOT NULL,
  modification_time datetime DEFAULT NULL
);

用数据

填充Table
insert into instrument_bit_detail(id, instrument_id, modification_time) values(1,10, CURRENT_DATE);
insert into instrument_bit_detail(id, instrument_id, modification_time) values(2,11, CURRENT_DATE);
insert into instrument_bit_detail(id, instrument_id, modification_time) values(3,10, CURRENT_DATE);
insert into instrument_bit_detail(id, instrument_id, modification_time) values(4,12, CURRENT_DATE);
insert into instrument_bit_detail(id, instrument_id, modification_time) values(5,11, CURRENT_DATE);
insert into instrument_bit_detail(id, instrument_id, modification_time) values(6,10, CURRENT_DATE);
insert into instrument_bit_detail(id, instrument_id, modification_time) values(7,12, CURRENT_DATE);

Select输出

ID      INSTRUMENT_ID   MODIFICATION_TIME  
1       10              2020-12-22 00:00:00
2       11              2020-12-22 00:00:00
3       10              2020-12-22 00:00:00
4       12              2020-12-22 00:00:00
5       11              2020-12-22 00:00:00
6       10              2020-12-22 00:00:00
7       12              2020-12-22 00:00:00

运行删除

DELETE FROM instrument_bit_detail t1 WHERE t1.id > (SELECT MIN(t2.id) FROM instrument_bit_detail t2 WHERE t1.instrument_id = t2.instrument_id );

Select删除后输出

ID      INSTRUMENT_ID   MODIFICATION_TIME  
1       10              2020-12-22 00:00:00
2       11              2020-12-22 00:00:00
4       12              2020-12-22 00:00:00