【问题标题】:Update column value using where order by in MySQL在 MySQL 中使用 where order by 更新列值
【发布时间】:2021-07-28 05:37:15
【问题描述】:

我有桌子tblOptionsAssets

它包含如下字段:

id (Primary Key)

position_id (simply the position number used to arrange data from position_id number 1 up to last row)

height (int)

我有样本记录

id | position_id | height

1 | 2 | 12

2 | 1 | 36

3 | 3 | 24

我想更新position_idASCENDINGLY,其中height 列按ASC 排序

预期输出:

id | position_id | height

1 | 1 | 12

2 | 3 | 36

3 | 2 | 24

如果我这样选择:

SELECT * FROM tblOptionsAssets ORDER BY position_id ASC

会返回类似的东西

id | position_id | height

1 | 1 | 12

3 | 2 | 24

2 | 3 | 36

更新

在我当前的设置中,有这样的行:

id | position_id | height

1 | 2 | 12

2 | 1 | 36

3 | 3 | 24

4 | 4 | 36

5 | 5 | 36

【问题讨论】:

    标签: mysql


    【解决方案1】:

    我建议实际上不要进行此更新,因为您可以轻松地使用ROW_NUMBER 以及在此处生成您想要的排序。例如:

    SELECT
        id,
        ROW_NUMBER() OVER (ORDER BY height) AS position_id,
        height
    FROM yourTable
    ORDER BY id;
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      相关资源
      最近更新 更多