Postgres分组然后从该组中随机显示一个

时间:2016-05-12 14:02:13

标签: postgresql

我有一个记录表,每个记录都属于一个集合。 我想列出集合,每个集合都有一个来自该集合的随机记录。

目前我有一个计数,但我想从记录表中返回随机ID。我无法理解它。有什么建议吗?

当前查询。

 select
   collections.name,collections.id, count(records.id) as count
 from
   collections, records
 where
   records.collection_id = collections.id
 group by
   collections.id
 order by
   collections.name

1 个答案:

答案 0 :(得分:0)

从上面的评论中添加答案

select collections.id AS random.id from collections, records 
 where records.collection_id = collections.id 
  OFFSET floor(random()* (select count(*) from collections, records 
                          where records.collection_id = collections.id ))
  LIMIT 1;