昨天我问了这个问题,但这对我没有帮助。我再次问它,希望这次我的问题更清楚。我试图通过使用WHEN,THEN,ELSE情况更新MySQL中的多行。我试图在后端使用python和Django来实现这一点。这是我的代码:
UPDATE priority
SET priority_order =
CASE priority_order
WHEN 4 THEN 8
WHEN 1 THEN 4
WHEN 3 THEN 2
## More X amount of WHEN/THEN statements
ELSE priority_order
END
问题是我不知道有多少WHEN和THEN行。我怎样才能构造这样一个语句,以便我可以使用cursor.execute()来执行它?
昨天,有人建议建立一个表达式列表并作为参数传递,如:
from django.db.models import Case, When
# Make a list of When expressions
when_list = [When(priority_number=2, then=3),
When(priority_number=3, then=4)]
# Use in a query of your choice, as an example:
Model.objects.update(
priority_number=Case(
*when_list))
但似乎它对Mysql不起作用。我认为这只适用于SQLLite。当我的查询执行时,* when_list没有被解码。请帮忙!
答案 0 :(得分:0)
你能尝试一下吗?
when_data = [(2, 3), (3, 4), ] # Your method for generate the data
when_list = [When(priority_number=a, then=b) for a, b in when_data]
default = 90000 # Your value here
# Change YourModel
qs = YourModel.objects.update(priority_number=Case(
*when_list,
default=default
))
# Now you can look on sql string
from django.db import connection
print (connection.queries[-1])