我需要根据表中的 PilotId 更新一个序列号从 1 开始的列。我从上一个问题中得到了答案……但是显然我不能在我的表达式中使用 CTE 函数或 *,在我的表达式中使用 php 和 mysqli MariaDB。
A) 有人知道为什么我不能使用 CTE 或 *, 吗?
B)有没有办法解决这个问题/为每个pilotID迭代的另一种方法是什么?
设置:PlaneID 为 NULL 开始。因此,对于 PilotID 的每一行,我需要更新 PlaneID 以从 1 开始并依次更新,以便我的数据像这样出来。该表被称为“飞行”。
我收到的错误。*,
错误更新记录:您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 3 行的“from ( select * , NewPlaneId = row_number...”附近使用正确的语法
数据:
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
下面的解决方案使用 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;
结果: 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 |
+-------+---------+---------+
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句