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更新类型客户起始序列的排序位置。