Python多个数据库导致一次更新

时间:2018-01-02 18:17:04

标签: python mysql sql sql-update

我想在一行中更新几个数据库结果。

我的代码:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {

        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        }
        alert.addAction(UIAlertAction(title: actionTitle, style: .destructive, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
                actionHandler?(nil)
                return
            }
            actionHandler?(textField.text)
        }))
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))

        self.present(alert, animated: true, completion: nil)
    }
}

示例输出:

  • 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

如何更新我的表格以便结束以下结果?

表格结构

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,256,258; TestName4,TestName5,TestName6; test@testname4.com,test@testname5.com,test@testname6.com
  • 3; 188; TestName7; test@testname7.com

1 个答案:

答案 0 :(得分:1)

考虑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;

但是,目前尚不清楚如何运行 update ,因为原始表中的行数多于聚合查询上的行数。考虑从上面的查询创建一个新表:

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;