简体   繁体   English

如何从python中的两个不同的sqlite3表中减去值

[英]How to subtract values from two different sqlite3 tables in python

Assuming i have a main table containing a list of items and quantities. 假设我有一个包含项目和数量列表的主表。 And a second table having also a list of items and quantities. 第二张表也列出了物品和数量。 Eg. 例如。

Main Table(Stock)(Table1) 主表(库存)(表1)

----------
Items  | QTY
----------
sugar  | 14
mango  | 10
apple  | 50
berry  | 1

Second Table(populated by user input)(Table 2) 第二个表(由用户输入填充)(表2)

----------
Items  |QTY
----------
sugar  |1
mango  |5
apple  |8
berry  |1

How do i get the item and quantity from the table 2, compare the item name with that of Table 1,such that if same it moves on to subtract Table 2's value from that of Table 1 In summary, how do i subtract values from two different tables in sqlite3 python Any ideas would help so much. 我如何从表2中获得项目和数量,将项目名称与表1中的名称进行比较,以使该名称和名称继续从表1中减去表2的值。总之,我如何从两个表中减去值sqlite3 python中的不同表任何想法都会有很大帮助。 A simple code example would also help much.Thank you 一个简单的代码示例也有很大帮助。谢谢

You can use replace into with join : 您可以将join replace into join

replace into Stock(Items, qty)    
select s.Items,
    s.qty - t.qty
from Stock s
join Second_table t on s.Items = t.Items;

The above works if there is a unique key defined on the Items column. 如果在“项目”列上定义了唯一键,则以上方法适用。

You can try using correlated subquery: 您可以尝试使用相关子查询:

update stock
set qty = qty - (
        select sum(qty)
        from second_table t
        where stock.items = t.items
        )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM