MySQL在一个查询中选择并更新

Dav*_*dJB 6 mysql mysql-python

我正在尝试从MySQL(total_points)中选择一个值,然后添加到局部变量(new_points)并更新SAME查询中的total_points,是否有人知道这是否可能...

我现在有.,

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()    
Run Code Online (Sandbox Code Playgroud)

ber*_*nie 1

问题是您的 SQL 语法不正确。查询应该是:

UPDATE g_ent 
SET total_points = total_points + %s
WHERE e_id = %s AND user = %s;
Run Code Online (Sandbox Code Playgroud)

完整的例子是:

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()
Run Code Online (Sandbox Code Playgroud)

请注意,查询参数的顺序已修改。