sqlite - 使用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;
您只需要 last closing_amount
,因此max(closing_amount)
从返回 1 行或根本没有的子查询中,将分别返回closing_amount
or null
。
查看简化的演示。
推荐阅读
- node.js - 在后续意图中获取与原始意图不匹配的参数值
- javascript - 如何在继续之前确保异步函数返回值
- java - 使用中位数 3 的快速排序中的逻辑错误
- python - 使用 Linux 子系统在 Python (os.subprocess) 中调用外部 bash 命令
- webgl - 获取 webGL2 片段着色器上的当前像素位置
- javascript - 如何在 d3 中从 v4 转换为 v3
- woocommerce - 在 woocommerce 帐户页面的下载选项卡上显示产品图片
- reactjs - docker 上没有 package.json
- repast-simphony - 在 Repast Symphony 中动态更改代理的边框颜色
- bash - 是否可以在 bash 脚本中包含 nohup 命令?