我尝试使用 CTE
WITH cte as (
SELECT myFieldName,
row_number() over (order by gps_device_id) as rn
FROM tracker.gps_devices
)
UPDATE cte
SET cte.myFieldName = CASE WHEN cte.rn % 3 = 0 THEN '0'
WHEN cte.rn % 3 = 1 THEN '1'
WHEN cte.rn % 3 = 2 THEN '2'
END
但是出现如下错误。
ERROR: relation "cte" does not exist
看起来我可以在 WITH
之后执行 INSERT
和 DELETE
但 UPDATE
只能在 cte 内部,是吗正确的?我确定我做了类似的事情,但可能在不同的数据库中。
https://www.postgresql.org/docs/9.6/static/queries-with.html
所以我就此结束,即使工作非常困惑,有什么建议吗?
UPDATE tracker.gps_devices g
SET g.myFieldName = CASE WHEN t.rn % 3 = 0 THEN '0'
WHEN t.rn % 3 = 1 THEN '1'
WHEN t.rn % 3 = 2 THEN '2'
END
FROM (SELECT gps_device_id,
myFieldName,
row_number() over (order by gps_device_id) as rn
FROM tracker.gps_devices) as t
WHERE g.gps_device_id = t.gps_device_id
最佳答案
您可以使用 cte 进行更新,例如(假设 id 是主键):
with cte as (
select
id,
my_field_name,
row_number() over (order by gps_device_id) as rn
from gps_devices
)
update gps_devices
set my_field_name = (rn % 3)::text
from cte
where gps_devices.id = cte.id;
您可以插入、更新或删除表( View )的行,而不是查询的结果集。
关于sql - 我可以更新 cte 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371844/