python - Sqlite3 - UPDATE Column by Lookup
问题描述
I am trying to lookup and update Market_Sector column in Accounts from MarketSector in Clients. The key columns are Client in Accounts Table and Id in Clients in Table. I have written the below code, but the look up only returns None! Please help!
import sqlite3
con = sqlite3.connect('''C:\\Users\\Bank DB1.db''')
cur = con.cursor()
cur.execute('''ALTER TABLE Accounts ADD Market_Sector''')
cur.execute('''UPDATE Accounts
SET Market_Sector = (SELECT MarketSector FROM Clients
WHERE Client = (SELECT Id FROM Clients))''')
con.commit()
con = sqlite3.connect('''C:\\Users\\Bank DB1.db''')
cur.execute('''SELECT * FROM Accounts''')
results = cur.fetchall()
print(results)
con.close()
解决方案
Use aliases for the tables so that the subquery is properly correlated:
UPDATE Accounts AS a
SET Market_Sector = (
SELECT c.MarketSector
FROM Clients AS c
WHERE c.Id = a.Client
)
Or with proper use of the table names:
UPDATE Accounts
SET Market_Sector = (
SELECT Clients.MarketSector
FROM Clients
WHERE Clients.Id = Accounts.Client
)
推荐阅读
- python - 如何在特定标签之前/之前获取 n 个索引号?
- r - R ifelse 基于满足两个标准的观察
- mongodb - 如何使用 URI 导出数据库中的所有集合?
- python - 为什么我的类的变量对于每个对象都不是唯一的?
- laravel - 自定义电子邮件验证通知
- latex - tikz png 输出不输出 png
- c# - 将对象类型从 IEnumerable 更改为 IQueryable 后,开始接收 LINQ 上下文错误
- algorithm - 找到最接近给定 3D 线集的点的算法
- c# - 如何让 Coroutine Timer 更流畅
- reactjs - 'stepped' paginationType 在控制台中产生 React 警告