我需要使用从另一个表中删除的值来更新表。情况是类似于SO 上的评论投票记分员。我正在使用 python 来处理 postgres,但这应该没有什么区别。
query="""
UPDATE comment SET score=score-(DELETE FROM history
WHERE commentId=%(commentId)s AND
userIdentity=%(userIdentity)s RETURNING vote)
WHERE commentId=%(commentId)s;
"""
cursor.execute(query, data)
错误出现在(DELETE FROM
;出现语法错误。我可以更换DELETE
声明与SELECT
声明并且它会起作用,我在这里缺少什么吗?我想在更新中使用返回值。这可能吗?任何事情都有帮助。
相关架构:
CREATE TABLE history (
commentId bigint,
vote int,
userIdentity varchar(256),
);
CREATE TABLE comment (
id bigint,
score bigint,
);
历史投票通常是1
or -1
.
PostgreSQL 不允许将 UPDATE 和 DELETE 语句混合作为子查询。
您可以使用稍微不同的策略 - 可更新的 CTE
postgres=# WITH t1 AS (DELETE FROM foo RETURNING *),
t2 AS (INSERT INTO deleted
SELECT * FROM t1 RETURNING *)
SELECT max(a) FROM t2;
so
postgres=# CREATE TABLE comment(id int, score int);
CREATE TABLE
postgres=# CREATE TABLE history(id int, comment_id int, vote int);
CREATE TABLE
postgres=# INSERT INTO comment values(1,10);
INSERT 0 1
postgres=# INSERT INTO comment values(2,20);
INSERT 0 1
postgres=# INSERT INTO history values(1,1,5);
INSERT 0 1
postgres=# WITH t1 AS (DELETE FROM history
WHERE id=1
RETURNING comment_id, vote)
UPDATE comment SET score=score-t1.vote
FROM t1
WHERE t1.comment_id=comment.id;
UPDATE 1
postgres=# select * from comment;
id | score
----+-------
2 | 20
1 | 5
(2 rows)
注意:需要9.1或更高版本
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)