psycopg2.errors.AmbiguousColumn:列引用 "words" 不明确

psycopg2.errors.AmbiguousColumn: column reference "words" is ambiguous

我正在尝试将 PostgreSQL 与 Python (v3.9.4) 连接。

这是我的代码片段:

content = 'this is a message'
user = 'Random User'
num_words = len(content.split())
cursor.execute('''
        INSERT INTO Rankings (UserName, Words)
            VALUES (%s, %s)
        ON CONFLICT (UserName)
        DO UPDATE
            SET Words = Words + %s
        ''', (user, num_words, num_words))

我已经正确创建了 PostgreSQL 连接和游标对象。并创建了一个 table 以及 2 列 - UserName 和 Words。

但是,我一直运行进入同样的错误:

psycopg2.errors.AmbiguousColumn: column reference "words" is ambiguous
LINE 6:             SET Words = Words + 1
^

当我将 SET Words = Words + %s 更改为 SET Words = %s 时,一切正常。如何在不导致此错误的情况下增加 Words 的现有值?

看起来这个错误的答案是在命名你指的是哪个 table 的专栏时总是具体的,即使只有一个 table.

我改写 SET Words = Rankings.Words + %s 来修正它。

根据文档 ON CONFLICT:

The SET and WHERE clauses in ON CONFLICT DO UPDATE have access to the existing row using the table's name (or an alias), and to rows proposed for insertion using the special excluded table.

因此您必须使用 table 名称或特殊的 table EXCLUDED.

来限定该列