Postgres:在列上选择Distinct不会通过Joins返回不同的结果

编程入门 行业动态 更新时间:2024-10-13 04:19:14
本文介绍了Postgres:在列上选择Distinct不会通过Joins返回不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在建立一个包含以下表格的系统:

I'm building a system in which there are the following tables:

  • 歌曲
  • 广播
  • 关注
  • 用户

用户关注电台,电台通过广播播放歌曲.

A user follows stations, which have songs on them through broadcasts.

我正在根据用户关注的电台为他们构建歌曲的供稿".

I'm building a "feed" of songs for a user based on the stations they follow.

以下是查询:

SELECT DISTINCT ON ("broadcasts"."created_at", "songs"."id") songs.* FROM "songs" INNER JOIN "broadcasts" ON "songs"."shared_id" = "broadcasts"."song_id" INNER JOIN "stations" ON "broadcasts"."station_id" = "stations"."id" INNER JOIN "follows" ON "stations"."id" = "follows"."station_id" WHERE "follows"."user_id" = 2 ORDER BY broadcasts.created_at desc LIMIT 18

正如您在此处看到的那样,我收到的重复歌曲正在发生,因为我正在跟踪两个都广播了同一首歌曲的电台:

As you can see here, I'm getting duplicate songs which is happening because I'm following two stations that BOTH have broadcasted that same song:

注意:shared_id与id相同.

Note: shared_id is the same as id.

我的问题是:如何修改此查询,使其仅根据其ID(或shared_id)返回唯一的歌曲?

推荐答案

从DISTINCT谓词中删除"broadcasts"."created_at",因为它返回非唯一值,因此重复了songs.如果您需要使用此信息进行排序,请创建一个新问题.

Remove "broadcasts"."created_at" from the DISTINCT predicate because it is returning non-unique values, hence duplicate songs. If you need to use this information to sort please create a new question.

更多推荐

Postgres:在列上选择Distinct不会通过Joins返回不同的结果

本文发布于:2023-10-26 18:20:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Postgres   Distinct   Joins

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!