Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql。如何使用从0到满足WHERE条件的最后一行的整数范围更新列_Postgresql_Postgresql 9.5 - Fatal编程技术网

Postgresql。如何使用从0到满足WHERE条件的最后一行的整数范围更新列

Postgresql。如何使用从0到满足WHERE条件的最后一行的整数范围更新列,postgresql,postgresql-9.5,Postgresql,Postgresql 9.5,我有一个下一个表示例,名为userz: +----+---------------+----------+ | id | sort_position | type | +----+---------------+----------+ | 1 | -5 | admin | | 2 | -3 | customer | | 3 | 1 | customer | | 4 | 8 | emp

我有一个下一个表示例,名为
userz

+----+---------------+----------+
| id | sort_position | type     |
+----+---------------+----------+
|  1 |            -5 | admin    |
|  2 |            -3 | customer |
|  3 |             1 | customer |
|  4 |             8 | employee |
|  5 |           200 | customer |
+----+---------------+----------+
使用
Mysql
如果我想将所有
customer
类型的
sort\u position
从0和
++
开始,直到满足
WHERE
标准的最后一行,我可以执行以下操作:

SET @i=-1; 
UPDATE userz 
SET sort_position=@i:=@i+1 
WHERE type = "customer" ORDER BY sort_position;
我将收到预期的结果:

+----+---------------+----------+
| id | sort_position | type     |
+----+---------------+----------+
|  1 |            -5 | admin    |
|  2 |             0 | customer |
|  3 |             1 | customer |
|  4 |             8 | employee |
|  5 |             2 | customer |
+----+---------------+----------+
如您所见,所有客户现在都被分配了正确的
排序位置
为0,1,2

但是因为我在postgre工作,我需要用它达到同样的效果。到目前为止,我尝试的是:

DO $$
DECLARE  
   i integer := -1;   
BEGIN  
   UPDATE userz 
   SET sort_position=@i:=@i+1 
   WHERE type = "customer" ORDER BY sort_position;
END $$;
我在
=@i:=@i+1
周围有错误,尝试了我在谷歌上搜索到的不同格式
=i:=i+1
,但仍然没有运气

update userz k
set sort_position = 
     (select ROW_NUMBER() over(order by sort_position)-1 rnum
         from userz src
        where src.type ='customer'
          and id = k.id)

正确标记!!!如果这是
Postgres
,为什么我会看到
MySQL
标签????它们是完全不同的两种产品。此错误可能是由您的
订购者
引起的。在
UPDATE
中,
orderby
没有意义。它将从0到n更新类型客户起始序列的排序位置。