MySQL select and update in one query

余生颓废 提交于 2019-12-23 09:37:23

问题


I'm trying to select a value from MySQL (total_points) then add to a local variable (new_points) and update total_points in the SAME query, does anyone know if this is possible...

I currently have.,

cursor = database.cursor() 
cursor.execute("""SELECT total_points FROM g_ent WHERE e_id =%s AND user =%s;
UPDATE total_points = (total_points + %s)"""
,(e_id, user_name, new_points))
database.commit()    

回答1:


The issue is that your SQL syntax is not correct. The query should be:

UPDATE g_ent 
SET total_points = total_points + %s
WHERE e_id = %s AND user = %s;

The full example would then be:

cursor = database.cursor() 
cursor.execute("""UPDATE g_ent 
                  SET total_points = total_points + %s
                  WHERE e_id = %s AND user = %s;""",
               (new_points, e_id, user_name)) # order of params revised
database.commit()

Please note that the order of the query parameters was revised.




回答2:


UPDATE g_ent
SET total_points = total_points + %s
Where e_id = %s 
  AND user = %s


来源:https://stackoverflow.com/questions/16344013/mysql-select-and-update-in-one-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!