Python多个数据库导致一次更新
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python多个数据库导致一次更新相关的知识,希望对你有一定的参考价值。
我想在一行中更新几个数据库结果。
我的代码:
sql_client = "SELECT pd.prj_id, pd.dl_id, pd.name, pd.email FROM projects_doc pd JOIN reminder rm ON pd.prj_id = rm.prj_id WHERE doc_typ = 'assignment' ORDER BY pd.id ASC;"
result = cursor.execute(sql_client)
result = cursor.fetchall()
for row in result:
sql_prj_id = row['prj_id']
sql_dl_id = row['dl_id']
sql_dl_name = row['name']
sql_dl_email = row['email']
示例输出:
- 1,544,TestName1,test @ testname1.com
- 2,255,TestName4,test @ testname4.com
- 2,256,TestName5,test @ testname5.com
- 2,257,TestName6,test @ testname6.com
- 3,188,TestName7,test @ testname7.com
如何更新我的表以便结束以下结果?
表结构
prj_id, dl_id, dl_name, dl_email
最终结果(例子)
- 1; 544; TestName1; test@testname1.com
- 2; 255,256,258; TestName4,TestName5,TestName6; test @ testname4.com,test @ testname5.com,test @ testname6.com
- 3; 188; TestName7; test@testname7.com
答案
考虑mysql的方言特定的聚合函数group_concat:
SELECT pd.prj_id,
GROUP_CONCAT(pd.dl_id) AS grp_ids,
GROUP_CONCAT(pd.name) AS grp_name,
GROUP_CONCAT(pd.email) AS grp_email
FROM projects_doc pd
JOIN reminder rm ON pd.prj_id = rm.prj_id
WHERE doc_typ = 'assignment'
GROUP BY pd.prj_id
ORDER BY pd.id ASC;
但是,目前尚不清楚如何运行更新,因为原始表中的行数多于聚合查询上的行数。考虑从上面的查询创建一个新表:
CREATE TABLE new_table AS <above SELECT query>
或者更好地保留原始的长格式,从而提供更高效的存储,可伸缩性,查询可维护性和参照完整性,因为列中的嵌套列表通常用于报告而不是表结构。只需从此查询中创建一个视图。视图是存储查询,甚至可以在Python等应用程序级别使用,甚至可以自己查询。
CREATE VIEW new_view AS <above SELECT query>
SELECT * FROM new_view WHERE prj_id = 1;
以上是关于Python多个数据库导致一次更新的主要内容,如果未能解决你的问题,请参考以下文章