MySQL - 通过一次更新保存列表顺序

发布于 2024-10-17 01:09:35 字数 755 浏览 2 评论 0原文

是否可以对列表进行排序并在一次更新中保存顺序?

我尝试了这种方法:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

潇烟暮雨 2024-10-24 01:09:38

MySql 不允许使用 ORDER BY 进行多表更新。 Docs

您可以使用子查询代替:

UPDATE jos_vm_category c
    JOIN (
        SELECT category_id, (@row:=@row+1) rowNum
        FROM jos_vm_category, (SELECT @row:=0) dm
        ORDER BY category_name
    ) rs ON c.category_id = rs.category_id
SET c.list_order = rs.rowNum

或者,您可以将它们拆分为 2 个查询:

SELECT @row:=0;
UPDATE jos_vm_category
SET list_order = (@row:=@row+1)
ORDER BY category_name;

MySql does not permit a ORDER BY with a multiple table update. Docs

You can use a sub query instead:

UPDATE jos_vm_category c
    JOIN (
        SELECT category_id, (@row:=@row+1) rowNum
        FROM jos_vm_category, (SELECT @row:=0) dm
        ORDER BY category_name
    ) rs ON c.category_id = rs.category_id
SET c.list_order = rs.rowNum

Alternatively, you can split them into 2 queries:

SELECT @row:=0;
UPDATE jos_vm_category
SET list_order = (@row:=@row+1)
ORDER BY category_name;
孤独患者 2024-10-24 01:09:38

我想这就是您正在寻找的:

ALTER TABLE `jos_vm_category` ORDER BY `category_name`;

I think this is what you are looking for:

ALTER TABLE `jos_vm_category` ORDER BY `category_name`;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文