我正在尝试在 PostgreSQL 中执行以下操作
INSERT INTO blog_sums ( blog_id, date, total_comments)
SELECT blog_id, '2016-09-22', count(comment_id) as total_comments_update
FROM blog_comments
WHERE date = '2016-09-22'
GROUP BY blog_id
ON CONFLICT (blog_id ,date)
DO UPDATE SET blog_sums.total_comments = total_comments_update;
我在日期 + blog_id 上有唯一的密钥,但我不断收到错误:
错误:列“total_comments_update”不存在
在这种情况下,我正在寻找“正确”的方法和最有效的方法来更新重复/冲突
我的桌子是
blog_comments (blog_id, comment_id, comment, date)
blog_sums ( blog_id, date, total_comments) . unique on blog_id+date
Thanks
您无法从 select 中访问列别名DO UPDATE SET
条款。您可以使用excluded
表别名,其中包括由于冲突而无法插入的所有行:
INSERT INTO blog_sums ( blog_id, date, total_comments)
SELECT blog_id, '2016-09-22', count(comment_id) as total_comments_update
FROM blog_comments
WHERE date = '2016-09-22'
GROUP BY blog_id
ON CONFLICT (blog_id ,date)
DO UPDATE SET total_comments = excluded.total_comments;
So excluded.total_comments
最后一行指的是值total_comments
我们尝试插入但由于冲突而无法插入。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)