Postgres等同于基于订单的MySQL更新

时间:2019-05-16 11:45:04

标签: mysql postgresql

在MySQL中,很容易根据订单结果更新表,例如:

SET @counter=1;
UPDATE task SET priority = (@counter:=@counter+1) ORDER BY createdAt ASC;

PostgreSQL上的等效查询是什么?

1 个答案:

答案 0 :(得分:3)

您可以将UPDATEJOIN一起使用到由ROW_NUMBER()函数生成的行号表中(根据createdAt的顺序选择行号):

UPDATE task
SET priority = p.priority
FROM (SELECT createdAt, ROW_NUMBER() OVER (ORDER BY createdAt) AS priority
      FROM task) p 
WHERE p.createdAt = task.createdAt

Demo on dbfiddle