sql - Order by join column but use distinct on another -
i'm building system in there following tables:
- song
- broadcast
- station
- follow
- user
a user follows stations, have songs on them through broadcasts.
i'm building "feed" of songs user based on stations follow.
here's query:
select distinct on ("broadcasts"."created_at", "songs"."id") songs.* "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" "follows"."user_id" = 2 order broadcasts.created_at desc limit 18
note: shared_id same id.
as can see i'm getting duplicate results, don't want. found out previous question due selecting distinct on broadcasts.created_at.
my question is: how modify query return unique songs based on id but still order broadcasts.created_at?
try solution:
select a.maxcreated, b.* ( select bb.song_id, max(bb.created_at) maxcreated follows aa inner join broadcasts bb on aa.station_id = bb.station_id aa.user_id = 2 group bb.song_id ) inner join songs b on a.song_id = b.id order a.maxcreated desc limit 18
the from
subselect retrieves distinct song_id
s broadcasted stations user follows; gets latest broadcast date associated each song. have encase in subquery because have group by
on columns we're selecting from, , want unique song_id
, maxdate regardless of station.
we join result in outer query songs
table song information associated each unique song_id
Comments
Post a Comment