2016-05-12 22 views
0

我有一個記錄表,每個記錄都屬於一個集合。 我想列出集合,並且每個集合都有該集合的隨機記錄。Postgres group by,然後顯示該組中的一個隨機

目前我有一個計數,但我也想從記錄表中返回隨機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 
+0

http://stackoverflow.com/questions/5297396/quick-random-row-selection-in-postgres – awsome

+0

不是可能重複確定這是重複的,因爲鏈接不包含我可以看到的連接。 – latitudehopper

+0

以上問題,你的應該是像選擇collections.id AS random.id從集合,記錄 where records.collection_id = collections.id group by collections.id OFFSET floor(random()*(select count(* )from collections,records where records.collection_id = collections.id group by collections.id)) LIMIT 1; – awsome

回答

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;