【问题标题】:Update table column with row numbers without CTE or * ,使用不带 CTE 或 * 的行号更新表列,
【发布时间】:2021-06-16 09:29:16
【问题描述】:

我需要根据表中的 PilotId 更新一个序列号从 1 开始的列。我有上一个问题的答案......但显然我不能使用 CTE 函数或 *,在我的表达式中使用 php 和 mysqli MariaDB。
A) 有人知道为什么我不能使用 CTE 或 *, 吗?
B) 有没有办法解决这个问题/对每个 PilotID 进行迭代的另一种方法是什么?

设置:PlaneID 为 NULL 以启动。因此,对于 PilotID 的每一行,我需要将 PlaneID 更新为从 1 开始并按顺序更新,这样我的数据就会像这样出现。该表称为“飞行”。

我收到错误。 *,

错误更新记录:您的 SQL 语法有错误;检查 与您的 MariaDB 服务器版本相对应的手册 在 'from ( select * , NewPlaneId = row_number...' 在第 3 行

数据:

RowID  PilotID  PlaneID
1      A          1
2      B          1
4      A          2
5      B          2
6      C          1
7      A          3

代码:

$sql'
 update a
      set PlaneId = NewPlaneId
      from (
        select *
          ,  NewPlaneId = row_number() over (
                partition by PilotId
                order by [RowId]
          )
        from flight
          ) as a
';

// NOTE: I do substitute in the actual [RowId] ... flight_id

【问题讨论】:

    标签: mysql mariadb


    【解决方案1】:

    以下解决方案使用 row_number 函数:

    update A
    join (
        select RowID, row_number() over (partition by PilotID order by RowID) rn from A
    ) N on N.RowID = A.RowID
    SET PlaneID = rn;
    

    MariaDB fiddle

    结果:select * from A order by PilotID;

    +=======+=========+=========+
    | RowID | PilotID | PlaneID |
    +=======+=========+=========+
    | 1     | A       | 1       |
    +-------+---------+---------+
    | 3     | A       | 2       |
    +-------+---------+---------+
    | 6     | A       | 3       |
    +-------+---------+---------+
    | 2     | B       | 1       |
    +-------+---------+---------+
    | 4     | B       | 2       |
    +-------+---------+---------+
    | 5     | C       | 1       |
    +-------+---------+---------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 2018-01-24
      • 2013-12-04
      相关资源
      最近更新 更多