gpt4 book ai didi

sql - PostgreSQL UNION 仅忽略特定列的重复项

转载 作者:搜寻专家 更新时间:2023-10-30 23:01:39 26 4
gpt4 key购买 nike

我有帖子表和通知表。我希望通知表中的帖子被评分为 999999 而不是它们的原始分数。下面的查询给出了图片中的结果。红色的是通过通知联合起来的,其余的来自帖子。正如您所看到的,即使它们是联合布鲁斯也是重复的,因为分数不同 UNION 不会将它们计为重复项。我怎样才能让它们算作重复项并且只允许红色的。

enter image description here

UNIONUNION ALL 给出相同的结果,因为我正在更改联合通知部分的对象分值。我试过 DISTINCT ON (id) 但它不允许按分数排序,DISTINCT ON (id,score) 排序错误。

SELECT id, created_at, data, (data->>'score')::NUMERIC AS score
FROM posts
WHERE NOT EXISTS (
SELECT 1
FROM swipes
WHERE ((swipes.data)->>'post_id')::INT = posts.id
AND ((swipes.data)->>'user_id')::INT = 32)

UNION

SELECT DISTINCT ON (id) ((notifications.data)->>'post_id')::INT AS id, posts.created_at, posts.data, 9999999 AS score
FROM notifications, posts
WHERE ((notifications.data)->>'user_id')::INT = 32 AND posts.id = ((notifications.data)->>'post_id')::INT

ORDER BY score DESC

有没有办法让 UNION 仅检查 id 列的重复项?

最佳答案

您可以使用 CTE:

with CTE as ( your query without order by )
Select id, created_at, data, max(score) as score
from cte
Group by id, create_at, data
Order by ...

关于sql - PostgreSQL UNION 仅忽略特定列的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31882757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com