sql - 我可以更新 cte 吗?

标签 sql postgresql common-table-expression

我尝试使用 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 之后执行 INSERTDELETEUPDATE 只能在 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/

相关文章:

mysql - 不正确的日期时间值 : 'DEFAULT' using mysql in node. js

sql - 唯一索引有什么用?

postgresql - 在 postgresql 中创建空表

sql - 处理匿名用户和注册用户的正确方法

java - 如何在 JPA 中使用 Postgres JSONB 数据类型?

php - 准备好的陈述不存在

sql-server - SQL Server CTE 层次结构关键字搜索

sql - PostgreSQL:如果条件存在则选择所有具有条件的行,否则忽略条件并选择最早的行

sql - 递归 SQL 语句 (Postgresql) - 简化版

sql - 用 lag(N) 值填充 NULL 列值