MySQL - 通过一次更新保存列表顺序
是否可以对列表进行排序并在一次更新中保存顺序?
我尝试了这种方法:
UPDATE `jos_vm_category`,(SELECT @row:=0) AS init SET @row:=@row+1, list_order=@row ORDER BY `category_name` ASC
但出现错误:
1221 - UPDATE 和的使用不正确 排序方式
如果不清楚,我需要这个:
category_id | category_name | list_order
3 | A | 1
1 | B | 2
2 | C | 3
来自这个:
category_id | category_name | list_order
1 | B | 1
2 | C | 2
3 | A | 3
用一个更新。
所以 list_order 是表的一个字段,我必须在其中保存行的顺序。 (我已经有了解决方案,但是要等两天,如果没人回答我会发布。)
Is it possible to sort a list and save the order in a single update?
I tried this way:
UPDATE `jos_vm_category`,(SELECT @row:=0) AS init SET @row:=@row+1, list_order=@row ORDER BY `category_name` ASC
but got an error:
1221 - Incorrect usage of UPDATE and
ORDER BY
If it's not clear, I need this:
category_id | category_name | list_order
3 | A | 1
1 | B | 2
2 | C | 3
from this:
category_id | category_name | list_order
1 | B | 1
2 | C | 2
3 | A | 3
with a single UPDATE.
So list_order is a field of the table where I have to save the order of rows. (I already have the solution, but have to wait for 2 days, so I'll publish then if nobody answers the question.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MySql 不允许使用
ORDER BY
进行多表更新。 Docs您可以使用子查询代替:
或者,您可以将它们拆分为 2 个查询:
MySql does not permit a
ORDER BY
with a multiple table update. DocsYou can use a sub query instead:
Alternatively, you can split them into 2 queries:
我想这就是您正在寻找的:
I think this is what you are looking for: