Domanda

I have a table called users_import into which I am parsing and importing a CSV file. Using that table I want to UPDATE my users table if the user already exists, or INSERT if it does not already exist. (This is actually a very simplified example of something much more complicated I'm trying to do.)

I am trying to do something very similar to this: https://stackoverflow.com/a/8702291/912717

Here are the table definitions and query:

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);

That query gives this error:

psql:test.sql:23: ERROR:  column reference "id" is ambiguous
LINE 11:  WHERE NOT EXISTS (SELECT 1 FROM upsert WHERE upsert.id = us...
                                                       ^

Why is id ambiguous and what is causing it?

È stato utile?

Soluzione

The RETURNING * in the WITH upsert... clause has all columns from users and all columns from the joined table users_import. So the result has two columns named id and two columns named name, hence the ambiguity when refering to upsert.id.

To avoid that, use RETURNING u.id if you don't need the rest of the columns.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top