将其他 table 的值添加到 h2 中当前 table 的值

Adding value from other table to value of the current table in h2

我有一个tablemedicine,还有一个tablecart。两者都有一个字段名称 quantityid。 如果 id 相等

,我想将 cart.quantity 添加到 medicine.quantity

由于我正在将代码从 MySQL 转换为 h2,因此我尝试使用 MODE=MySQL 的 MySQL 兼容模式,但以下代码不起作用

update medicine, cart 
set medicine.quantity = medicine.quantity+cart.quantity 
where medicine.id = cart.id;

我尝试使用官方文档中给出的 select 语句

update medicine med1 
set med1.quantity = med1.quantity+
                   (select cart.quantity from cart where cart.id = med1.id)

我预计当 ID 匹配时输出是数量之和 但是在执行更新操作后,我在所有行的 medicine.quantity 中得到 NULL 值。

可以更改什么,以便在没有 id 匹配时 medicine.quantity 保持不变,或者在 id 匹配时添加 cart.quantity

该更新语句正在更新 table 中的所有记录。因此,如果购物车 table.

中没有 ID 的记录,med1.quantity 字段将更新为 NULL

你应该在so之后添加一个WHERE子句:

update medicine med1 
set med1.quantity = med1.quantity+
(select cart.quantity from cart where cart.id = med1.id)
where med1.id in (Select cart.id from cart)

我使用 where exists

解决了它
set quantity = quantity +
                (select quantity from cart where id = med1.id) 
where exists (select quantity from cart where id = med1.id)"