增加一个值,但不超过另一个值sql

时间:2019-05-24 17:05:37

标签: python mysql sql

您好,我正在尝试编写一条sql语句,以检查增加的值是否高于另一个值。

我正在使用MySQL和Python。

Response=int(input("Use Medicine? Y/N "))
if Response==("Y") or Response==("y"):
   healedvalue=random.randint(1,3)
   GetHealth=("UPDATE activechar SET currhealth=currhealth+%s BUT NOT HIGHER THAN currmaxhealth WHERE acharID=%s")
   mycursor.execute(GetHealth,(healedvalue,id))
   mydb.commit()

所需结果:

例如,如果currhealth=1healedvalue=3currmaxhealth=5,则currheath将更新为4

如果currhealth=4healedvalue=3currmaxhealth=5,则currheath将更新为5,因为currhealth不能超过{{1} }。

表格:

activechar table

1 个答案:

答案 0 :(得分:1)

您可以使用LEAST() function,它“返回最小(最小值)的参数”:

UPDATE activechar
SET currhealth = LEAST(currhealth + %s, currmaxhealth)
WHERE acharID = %s