使用sqlite中的最后一行插入数据库行时出现问题

Problem inserting database row using last row in sqlite

我希望能够在开始时以及随时执行以下操作。

insert into balance (closing_amount, opening_amount, created, tx_id)

select closing_amount + :value, closing_amount, :date, :tx_id from balance order by id desc limit 1

基本上我是通过使用以前的值来插入的。但是,如果没有值开头,则不会插入任何内容。

我可以使用第一次工作但在后续插入时重复的联合。

我想避免两次旅行。有办法吗?

此外,tx_id 将始终是唯一的。

我想你想要这样的东西:

insert into balance (closing_amount, opening_amount, created, tx_id)
select coalesce(max(closing_amount), 0) + :value, 
       coalesce(max(closing_amount), 0), 
       :date, 
       :tx_id 
from (       
  select closing_amount 
  from balance 
  order by tx_id desc
  limit 1
) t;

您只需要最后一个 closing_amount,因此子查询中的 max(closing_amount),即 return 1 行或 none,将 return分别是 closing_amountnull

查看简化版 demo