Postgres 给出关系不存在别名错误
Postgres giving relation does not exist error for alias
WITH TAB AS
(
SELECT id,flag FROM source where flag IS NULL and Data= '151234567890' ORDER BY 1 OFFSET
(
SELECT COUNT(*) FROM source where flag IS NULL and Data = '151234567890' ) - 96 FETCH FIRST 96 ROWS ONLY )
UPDATE TAB SET flag = 'Z';
以上查询在 MS Sql 中运行良好,但在 postgres
中 运行 时显示此错误
ERROR: relation "tab" does not exist
LINE 9: UPDATE TAB SET flag = 'Z';
在 MS Sql 服务器中可以更新 CTE。
在 Postgresql 中,您可以 link 到 CTE 进行更新。
例如:
WITH CTE AS (
SELECT id FROM source
WHERE Data= '151234567890'
AND flag IS NULL
ORDER BY id DESC
FETCH FIRST 96 ROWS ONLY
)
UPDATE source t
SET flag = 'Z'
FROM CTE c
WHERE t.id = c.id;
但是,此类更新假定 table 中的 ID 是唯一的。
但是,要标记最新的重复项,可以对其进行简化。
UPDATE source tgt
SET flag = 'Z'
FROM source src
WHERE src.Data = '151234567890'
AND tgt.Data = src.Data
AND tgt.id = src.id
AND tgt.ctid > src.ctid
AND tgt.flag IS NULL;
或者如果您想标记更高的金额。
使用 ROW_NUMBER 可能会有帮助。
WITH CTE AS (
SELECT ctid, id, Data, Amt
, ROW_NUMBER() OVER (PARTITION BY Data, id ORDER BY Amt) AS rn
FROM source
WHERE Data= '151234567890'
AND flag IS NULL
)
UPDATE source t
SET flag = 'Z'
FROM CTE c
WHERE c.rn > 1
AND t.id = c.id
AND t.Data = c.Data
AND t.ctid = c.ctid;
测试 db<>fiddle here
WITH TAB AS
(
SELECT id,flag FROM source where flag IS NULL and Data= '151234567890' ORDER BY 1 OFFSET
(
SELECT COUNT(*) FROM source where flag IS NULL and Data = '151234567890' ) - 96 FETCH FIRST 96 ROWS ONLY )
UPDATE TAB SET flag = 'Z';
以上查询在 MS Sql 中运行良好,但在 postgres
中 运行 时显示此错误ERROR: relation "tab" does not exist
LINE 9: UPDATE TAB SET flag = 'Z';
在 MS Sql 服务器中可以更新 CTE。
在 Postgresql 中,您可以 link 到 CTE 进行更新。
例如:
WITH CTE AS (
SELECT id FROM source
WHERE Data= '151234567890'
AND flag IS NULL
ORDER BY id DESC
FETCH FIRST 96 ROWS ONLY
)
UPDATE source t
SET flag = 'Z'
FROM CTE c
WHERE t.id = c.id;
但是,此类更新假定 table 中的 ID 是唯一的。
但是,要标记最新的重复项,可以对其进行简化。
UPDATE source tgt
SET flag = 'Z'
FROM source src
WHERE src.Data = '151234567890'
AND tgt.Data = src.Data
AND tgt.id = src.id
AND tgt.ctid > src.ctid
AND tgt.flag IS NULL;
或者如果您想标记更高的金额。
使用 ROW_NUMBER 可能会有帮助。
WITH CTE AS (
SELECT ctid, id, Data, Amt
, ROW_NUMBER() OVER (PARTITION BY Data, id ORDER BY Amt) AS rn
FROM source
WHERE Data= '151234567890'
AND flag IS NULL
)
UPDATE source t
SET flag = 'Z'
FROM CTE c
WHERE c.rn > 1
AND t.id = c.id
AND t.Data = c.Data
AND t.ctid = c.ctid;
测试 db<>fiddle here