PostgreSQL 9.3:从另一个表更新表(顺序列),在行中获得相同的值

时间:2018-07-19 14:05:16

标签: postgresql sql-update postgresql-9.1 postgresql-9.3

我需要有关从Postgres Db中的另一个表更新表的帮助。

长话短说,我们最终在db中破坏了数据,现在我需要用另一个表中的值更新一个表。

我有包含此数据table wfc的表:

| step_id | command_id | commands_order |
|---------|------------|----------------|
|       1 |          1 |              0 |
|       1 |          2 |              1 |
|       1 |          3 |              2 |
|       1 |          4 |              3 |
|       1 |          1 |              0 |
|       2 |          2 |              0 |
|       2 |          3 |              1 |
|       2 |          3 |              1 |
|       2 |          4 |              3 |

并且我想从另一个表更新command_order列中的值,所以我可以得到如下结果:

| step_id | command_id | commands_order|
|---------|------------|---------------|
|       1 |          1 |             0 |
|       1 |          2 |             1 |
|       1 |          3 |             2 |
|       1 |          4 |             3 |
|       1 |          1 |             4 |
|       2 |          2 |             0 |
|       2 |          3 |             1 |
|       2 |          3 |             2 |
|       2 |          4 |             3 |

这看起来很容易,但是问题是要为相同的command_id更新行,它正在commands_order中写入相同的值

我尝试的

SQL是:

UPDATE wfc 
SET commands_order = CAST(sq.input_step_id as INTEGER) 
FROM  ( 
SELECT wfp.step_id, wfp.input_command_id, wfp.input_step_id
from wfp 
order by wfp.step_id, wfp.input_step_id

   ) AS sq
WHERE  (wfc.step_id=sq.step_id AND wfc.command_id=CAST(sq.input_command_id as INTEGER));

SQL小提琴http://sqlfiddle.com/#!15/4efff4/4

我对此很坚持,请帮忙。

谢谢。

1 个答案:

答案 0 :(得分:0)

假设您尝试按创建顺序对行进行编号,并且只要您了解ctid将在更新时使用VACCUUM FULL进行更改,则可以执行以下操作:

select step_id, command_id, rank - 1 as command_order 
from (select step_id, command_id, ctid as wfc_ctid, rank() over
         (partition by step_id order by ctid)
      from wfc) as wfc_ordered;

这将为您提供wfc表以及所需的顺序。如果您确实更新了原始表,则ctid将会更改,因此使用上述查询创建表副本可能更安全。

相关问题