尝试在 PostgreSQL 中使用“CASE”时出错

Getting error when trying to use `CASE` in PostgreSQL

下午好,我正在尝试 运行 PgAdmin 中的查询来增加我的 table 中的值(如果存在),如果不存在,它将创建该行,我得到一个然而错误

ERROR:  syntax error at or near "CASE"
LINE 1: CASE 
        ^
SQL state: 42601
Character: 1
CASE 
    WHEN EXISTS(SELECT * FROM counter WHERE user_id = '321') THEN
        UPDATE counter
            SET counter = counter + 1
        WHERE user_id = '321'
    ELSE 
        INSERT INTO counter (user_id) VALUES ('321')  -- `counter` column is `SMALLINT DEFAULT 0`
END

我也试过使用 upsert

INSERT INTO cookies_counter (user_id) VALUES ('321')
ON CONFLICT (user_id) DO 
UPDATE SET counter = counter + 1
WHERE user_id = '321'

它给了我一个不同的错误

ERROR:  column reference "counter" is ambiguous
LINE 2: ON CONFLICT (user_id) DO UPDATE SET counter = counter + 1
                                                      ^
SQL state: 42702
Character: 100

类似这样的方法可能有效,但它在一定程度上取决于 table 结构:

CREATE  TABLE counter(user_id INT UNIQUE, counter smallint default 0);
INSERT INTO counter (user_id) 
VALUES ('321')
ON CONFLICT (user_id)
DO UPDATE
SET counter = counter.counter + 1::SMALLINT;