基于另一个表之间的匹配更新SQLite中的表

nwsw7zdq  于 2023-02-23  发布在  SQLite
关注(0)|答案(1)|浏览(207)

我想更新一个名为stock的表,其中product_id与另一个名为stock_in_temp的表的product_id匹配,并且名为crm_product_id的列必须是null''
我试了这个代码:

conn.execute("UPDATE stock SET stock.quantity += stock_in_temp.quantity FROM stock, stock_in_temp WHERE stock.product_id = stock_in_temp.product_id AND stock_in_temp.CRM_product_id !='' ")
sqlite3.OperationalError: near ".": syntax error
kjthegm6

kjthegm61#

你的语法错误。
=运算符左侧的更新列不能用表名限定。
此外,stock不应在FROM之后再次引用(这是一个逻辑错误,而不是语法错误),并且运算符+=可能在编程语言中有效,但在SQLite中无效。
变更为:

UPDATE stock AS s
SET quantity = s.quantity + t.quantity 
FROM stock_in_temp AS t 
WHERE s.product_id = t.product_id AND t.CRM_product_id <> '';

注意,如果quantitystock中是 * nullable *,则SET语句必须是:

SET quantity = COALESCE(s.quantity, 0) + t.quantity

我使用别名而不是表名来缩短代码。

相关问题