你觉得SQLite多表更新的写法很繁琐吗?

发表时间: 2021-09-06 12:58

SQLite是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite是一个增长最快的数据库引擎,这是在普及方面的增长,与它的尺寸大小无关。SQLite 源代码不受版权限制。

我们知道SQL92标准把数据库分为三个级别:基本集、标准集和完全集,SQLite基本上符合标准集,我在使用SQLite开发中,总觉着多表更新SQL很别扭。

结合实际开发,来说说SQLite多表更新。

1、SQLite 单表更新语法

UPDATE table_nameSET column1 = value1, column2 = value2...., columnN = valueNWHERE [condition];

【示例】(有效云开发平台模块实例)库存入库记录中,更新当前入库记录备注信息为当前操作者姓名:

update tb_store_in set memo= {{ME.realname}} where id ={{.id}}

有效云开发平台应用模块开发

2、SQLite多表更新

update table1 set fieldname1 = ( select table2.fieldname1 from table2 where table1.filename=table2.fieldname where ) ,fieldname2 = ( select table3.fieldname1 from tableb3 where table1.filename=table3.fieldname where ) where table1.filename2=value2

是不是看上去瞬间有种复杂的感觉?与 Update ta a,tb b set a.name=b.sname where a.id=b.did 相比复杂很多。

【示例】,来看一个典型的应用,库存入库:

update tb_store set goods_count = ifnull(goods_count,0) + (select tb_store_in.goods_count from tb_store_in where tb_store.goods_id=tb_store_in.goods_id and tb_store_in.id={{.id}}),memo =  (select tb_store_in.uid || '-' || tb_store_in.uname || '-' || tb_store_in.goods_count from tb_store_in where tb_store.goods_id=tb_store_in.goods_id and tb_store_in.id={{.id}}),logtime=(select tb_store_in.logtime from tb_store_in where tb_store.goods_id=tb_store_in.goods_id and tb_store_in.id={{.id}})where goods_id={{.goods_id}} ;

tb_store 为库存表,tb_store_in 为入库表,当提交了ru库操作,更新库存数量为,原库存数量 + 新入库数量,同时更新了 库存日志时间 logtime 为入库操作日志时间,并在备注中保存了操作者相关信息。

可能会觉着语句比较复杂,其实掌握了SQLite 多表联合更新的语法,根据业务逻辑需求,逐个字段处理并不难。例如,上面的示例,可以拆分为3个语句分别调试,调试先把系统环境变量改为常数。

-- {{.id}}=2 当前入库记录id为2-- {{.goods_id}} 用1 代替update tb_store set goods_count = ifnull(goods_count,0) + (select tb_store_in.goods_count from tb_store_in where tb_store.goods_id=tb_store_in.goods_id and tb_store_in.id=2) where goods_id=1;

调试通过,再调试第二个字段:

-- {{.id}}=2 当前入库记录id为2-- {{.goods_id}} 用1 代替update tb_store setmemo =  (select tb_store_in.uid || '-' || tb_store_in.uname || '-' || tb_store_in.goods_count from tb_store_in where tb_store.goods_id=tb_store_in.goods_id and tb_store_in.id=2),where goods_id=1;

逐个调试通过,把常量改为系统变量,再添加到模块扩展的相应位置。

你觉得SQLite可以作为简单业务数据库,用于企业管理系统中吗?