我希望对H2数据库表中的重复行进行操作(删除将是一次机会,请设置另一个新值)。
让我们准备一些示例数据:
COS(0) * COS(DIV(ACOS(-1),180) * Address_geolat) *
SIN(DIV(DIV(ACOS(-1),180) * (Address1_geolng - 0)), 2) * SIN(DIV(DIV(ACOS(-1),180) * (Address1_geolng - 0), 2)) AS a FROM restaurants WHERE (3959 * 2 * ATAN2(SQRT(a), SQRT(1 - a)) <= 10)
wich带我们去:
我认为这句话是足够的:
create table receipt( id int primary key, receipt_number varchar(52), shop_id int);
insert into receipt(id, receipt_number, shop_id) values(1,'A',1);
insert into receipt(id, receipt_number, shop_id) values(2,'A',1);
insert into receipt(id, receipt_number, shop_id) values(3,'B',1);
insert into receipt(id, receipt_number, shop_id) values(4,'A',2);
select * from receipt;
select receipt_number, shop_id, count(*) count from receipt group by (receipt_number, shop_id);
但会引发异常:
merge into receipt as t1
using ( select receipt_number, shop_id, count(*) count from receipt group by (receipt_number, shop_id) ) as t2 on t1.receipt_number = t2.receipt_number
when matched and count > 1 then delete;
您可以轻松测试我的代码运行情况
Syntax error in SQL statement "MERGE INTO RECEIPT AS T1
USING ( SELECT RECEIPT_NUMBER, SHOP_ID, COUNT(*) COUNT FROM RECEIPT GROUP BY (RECEIPT_NUMBER, SHOP_ID) ) AS T2 ON T1[*].RECEIPT_NUMBER = T2.RECEIPT_NUMBER
WHEN MATCHED AND COUNT > 1 THEN DELETE "; expected "("; SQL statement:
merge into receipt as t1
using ( select receipt_number, shop_id, count(*) count from receipt group by (receipt_number, shop_id) ) as t2 on t1.receipt_number = t2.receipt_number
when matched and count > 1 then delete [42001-197] 42001/42001
浏览至docker run -d -p 1521:1521 -p 8082:81 oscarfonts/h2
登录并复制并粘贴代码。
答案 0 :(得分:0)
我想我用
解决了delete receipt
where id > (select min(id) from receipt t2 where receipt.receipt_number = t2.receipt_number and receipt.shop_id = t2.shop_id )
猜我也可以将其用于update
。
答案 1 :(得分:0)
当心:Irkwz的答案会删除所有ID最低的条目,但ID最低的条目除外(至少在我的试验中是这样的。
这是一个更好的解决方案(在H2上进行了测试),但仍不完美,因为它每次执行时每个约束只删除一个重复项:
delete from receipt
where id in (
select max(t2.id)
from receipt t2
group by t2.receipt_number, t2.shop_id
having count(t2.id) > 1
);