我正在尝试通过更新或插入新记录来更新数据库投票用户表。该表定义如下:
Column | Type | Modifiers
-----------+---------+--------------------------------------------------------------
id | integer | not null default nextval('vote_user_table_id_seq'::regclass)
review_id | integer | not null
user_id | integer | not null
positive | boolean | default false
negative | boolean | default false
Indexes:
"vote_user_table_pkey" PRIMARY KEY, btree (id)
这是我正在使用的查询。实际上,我对所有值都使用了参数,但出于测试目的,我将它们替换为我确信应该有效的值。用户名[电子邮件受保护] /cdn-cgi/l/email-protection exists.
WITH updated AS (
UPDATE vote_user_table
SET
positive = 'true',
negative = 'false'
FROM usuario
WHERE
review_id = 6 AND
user_id = usuario.id AND
usuario.username ILIKE '[email protected] /cdn-cgi/l/email-protection'
RETURNING vote_user_table.id
)
INSERT INTO vote_user_table
(review_id, user_id, positive, negative)
SELECT 6, usuario.id, 'true', 'false'
FROM usuario, updated
WHERE
updated.id IS NULL AND
usuario.username ILIKE '[email protected] /cdn-cgi/l/email-protection'
运行查询后获得的输出是:
INSERT 0 0
尽管它应该插入新值,因为数据库中尚不存在该行。当我仅使用 insert 子句手动插入行,然后执行上面所示的 upsert 查询时,它正确更新了该行。
我使用的是 PostgreSQL 版本 9.2.4。
我从另一个问题中得到了编写此查询的想法:
在 PostgreSQL 中重复更新时插入? https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-postgresql
关于我可能做错了什么有什么想法吗?
关于如何实现我想做的事情有什么建议吗?
创建声明投票用户表:
CREATE TABLE vote_user_table (
id integer NOT NULL,
review_id integer NOT NULL,
user_id integer NOT NULL,
positive boolean DEFAULT false,
negative boolean DEFAULT false
);
CREATE SEQUENCE vote_user_table_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER SEQUENCE vote_user_table_id_seq OWNED BY vote_user_table.id;