1

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

  • Song
  • Broadcast
  • Station
  • Follow
  • User

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.

Here's the query:

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:

sql not working distinct on join

Note: shared_id is the same as id.

My question is: How do I modify this query so it will return only unique songs based on their id (or shared_id)?

7
  • What happens if you return "broadcasts"."created_at" in the SELECT? Jul 6, 2012 at 23:27
  • No change, I just get that value returned as well. Jul 6, 2012 at 23:49
  • Sorry I should have added to my first comment: Is the returned created_at unique on every row? Jul 6, 2012 at 23:51
  • Yea it is, I only have it in the distinct because I am using it in in the order, but its not a problem as its pretty much (totally?) impossible for two songs to have the same exact time anyway. Jul 7, 2012 at 0:35
  • That's exactly the issue. You're selecting distinct on a field that is pretty much guaranteed to be unique. You should probably remove that from the distinct clause. Jul 7, 2012 at 0:42

1 Answer 1

3

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.