2017-06-02 43 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()是隨機的。 –