我在 Postgres 表中有一个排序列,我试图在运行中用 SQL 重新排序该列。在 MySQL 中,我只运行这个查询:
SET @new_ordering = 1;
UPDATE grados SET g_order = (@new_ordering := @new_ordering + 1) ORDER BY g_order ASC;
当然这在 Postgres 中不起作用。我将如何在 Postgres 中运行类似的操作来使用新的增量值更新排序列?
最佳答案
这可以使用 Postgres 中的窗口函数轻松完成:
update grados
set g_order = t.rn
from (
select pk_column,
row_number() over (order by g_order) as rn
from grados
) t
where t.pk_column = grados.pk_column;
您需要将 pk_column
替换为您真正的主键列以获得正确的连接。
SQLFiddle:http://sqlfiddle.com/#!15/14a67/1
关于postgresql - 在 PostgreSQL 9.3 中重新编号排序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28308186/