2017-06-02 39 views
1
不重复属性两个随机行

比方说,我有客户地址表:返回PostgreSQL中

Name   | AddressLine 
------------------------------- 
John Smith  | 123 Nowheresville 
Jane Doe  | 456 Evergreen Terrace 
John Smith  | 999 Somewhereelse 
Joe Bloggs  | 1 Second Ave 

我想从这个表中返回两个随机行,但我不希望返回两行以相同的名称(我不想要的例子):

Name   | AddressLine 
------------------------------- 
John Smith  | 123 Nowheresville 
John Smith  | 999 Somewhereelse 

我该如何在Postgres中做到这一点?

回答

3

这里有一个方法:

select distinct on (name) t.* 
from t 
order by name, random(); 
+0

将是有史以来返回第二行的约翰·史密斯? '999 Somewhereelse'? –

+0

@LukeSchlangen。 。 。它可以。 random()是随机的。 –