首页 > 解决方案 > 使用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 将始终是唯一的。

标签: sqlitesql-insertinsert-update

解决方案


我想你想要这样的东西:

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;

您只需要 last closing_amount,因此max(closing_amount)从返回 1 行或根本没有的子查询中,将分别返回closing_amountor null

查看简化的演示


推荐阅读