Postgresql SELECT random with unique value

情到浓时终转凉″ 提交于 2019-12-11 03:23:46

问题


I am not able to make one clean SELECT

I have postgresql table with fields id , providerid, deal_name

I want to make random select with unique providerid

SELECT * FROM deals ORDER BY random() LIMIT 10

How I can set this to return 10 results with unique providerid's ?


回答1:


Can your question be rephrased as:

"For each of ten randomly selected providers, find one randomly selected deal offered by that provider" ?

If so, that pretty much tells you what to do. You need two layers, one pass to randomly select ten providers, then one pass to select one random deal per provider.

Given dummy data:

create table spam ( deal text, provider text );

insert into spam(deal,provider) 
SELECT prov_id||n::text, prov_id FROM (
    SELECT chr(x) AS prov_id from  generate_series(97, 92+26) x) y 
CROSS JOIN generate_series(1,10) n;

select provider FROM spam GROUP BY provider ORDER BY random() LIMIT 10;

Here's one that works:

SELECT
 (SELECT deal FROM spam WHERE spam.provider = sel_prov.provider ORDER BY random() LIMIT 1),
 sel_prov.provider
FROM (select provider FROM spam GROUP BY provider ORDER BY random() LIMIT 10) sel_prov;

... pretty much just by implementing the phrasing above as SQL. Don't know if it's fast; you get the idea.

If the above rephrasing isn't correct, please clarify your question with sample data and an example, or some more detail in your description.




回答2:


If the rephrasing proposed by @Craig Ringer is correct:

For each of ten randomly selected providers, find one randomly selected deal offered by that provider

then I can suggest another solution:

SELECT d.id, d.providerid, d.deal_name FROM (SELECT DISTINCT ON (providerid) providerid , id, deal_name FROM deals) d ORDER BY random() LIMIT 10;

I hope it will help!



来源:https://stackoverflow.com/questions/12007297/postgresql-select-random-with-unique-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!