我有一个表users_import
,我正在解析和导入 CSV 文件。使用该表,如果用户已经存在,我想更新我的users
表,或者如果它不存在,则插入。(这实际上是我正在尝试做的更复杂的事情的一个非常简化的例子。)
我正在尝试做与此非常相似的事情: https ://stackoverflow.com/a/8702291/912717
以下是表定义和查询:
CREATE TABLE users (
id INTEGER NOT NULL UNIQUE PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE users_import (
id INTEGER NOT NULL UNIQUE PRIMARY KEY,
name TEXT NOT NULL
);
WITH upsert AS (
UPDATE users AS u
SET
name = i.name
FROM users_import AS i
WHERE u.id = i.id
RETURNING *
)
INSERT INTO users (name)
SELECT id, name
FROM users_import
WHERE NOT EXISTS (SELECT 1 FROM upsert WHERE upsert.id = users_import.id);
该查询给出了这个错误:
psql:test.sql:23: ERROR: column reference "id" is ambiguous
LINE 11: WHERE NOT EXISTS (SELECT 1 FROM upsert WHERE upsert.id = us...
^
为什么id
模棱两可,是什么原因造成的?