如何随机化DISTINCT ON结果的顺序?

时间:2014-08-20 17:10:19

标签: sql postgresql activerecord

我有一个播客剧集表

id | title | podcast_id | publication_date
 1 |   "a" |          1 |            today
 2 |   "b" |          2 |            today
 3 |   "c" |          1 |            yesterday
 4 |   "d" |          2 |            yesterday

通过此查询,我可以收听每个播客的最新剧集。

SELECT DISTINCT ON (episodes.podcast_id) episodes.* FROM "episodes"
WHERE ...
ORDER BY episodes.podcast_id, "episodes"."publication_date" DESC

结果

id | title | podcast_id | publication_date
 1 |   "a" |          1 |            today
 2 |   "b" |          2 |            today

我希望随机化返回的播客的顺序,以便在{1}之前返回podcast_id 2,但在最终的RANDOM()子句中添加ORDER BY会更改哪个选择播客的剧集。

总结一下:我想以随机顺序来播放每个播客的最新剧集。

编辑:我应该提一下,这个查询是将许多ActiveRecord范围链接在一起的结果。以下是转换为ActiveRecord的最终答案

# This ActiveRecord statement is equivalent to the above SQL query
episodes = Episode
  .unscoped
  .select("DISTINCT ON (episodes.podcast_id) episodes.*")
  .order("episodes.podcast_id, episodes.publication_date")

Episode
  .unscoped
  .from("(#{sql.to_sql}) episodes")
  .order("random()")

我不确定这是否是一种很好的方法。我看到它们的优点是

  1. 单一查询
  2. 结果是ActiveRecord_Relation,您可以继续链接limitpluck

1 个答案:

答案 0 :(得分:3)

select *
from (
    SELECT DISTINCT ON (episodes.podcast_id) episodes.*
    FROM "episodes"
    WHERE ...
    ORDER BY episodes.podcast_id, "episodes"."publication_date" DESC
) s
order by random()