PostgreSQL DISTINCT 和 DISTINCT ON

select語句中,使用distinct關鍵字,在處理select list後,結果表能夠選擇消除重複的行。在SELECT以後直接寫入DISTINCT關鍵字以指定此關鍵字:sql

SELECT DISTINCT select_list ...

(能夠使用關鍵字ALL代替DISTINCT來指定保留全部行的默認行爲)express

 

顯然,若是兩行至少有一個列值不一樣,則認爲它們是不一樣的。在此比較中,將空值視爲相等。函數

 

另外,一個任意表達式能夠肯定哪些行被認爲是不一樣的:code

SELECT DISTINCT ON (expression [, expression ...]) select_list ...

這裏的expression是一個針對全部行求值的任意值表達式。 一組全部表達式均相等的行被視爲重複行,而且僅該集合的第一行保留在輸出中。請注意,除非查詢在足夠的列上排序以保證到達DISTINCT過濾器的行的惟一順序,不然集合的「第一行」是不可預測的。(DISTINCT ON處理在ORDER BY排序以後進行)blog

DISTINCT ON子句不是SQL標準的一部分,有時因爲其結果的不肯定性而有時被認爲是不良樣式。經過明智地使用GROUP BYFROM中的子查詢,能夠避免這種構造,可是它一般是最方便的選擇。排序

 

create table t_distinct(a int ,b int ,c int);
insert into t_distinct values(1,2,3);
insert into t_distinct values(2,3,4);
insert into t_distinct values(3,4,5);

insert into t_distinct values(2,2,3);
insert into t_distinct values(3,3,4);
insert into t_distinct values(4,4,5); 

insert into t_distinct(a,b) values(5,6); 
insert into t_distinct(a,b) values(5,6); 
insert into t_distinct(a,b) values(6,7); 

  

1.返回全部記錄:it

# select a,b,c from t_distinct;
 a | b | c 
---+---+---
 1 | 2 | 3
 2 | 3 | 4
 3 | 4 | 5
 2 | 2 | 3
 3 | 3 | 4
 4 | 4 | 5
 5 | 6 |  
 5 | 6 |  
 6 | 7 |  
(9 rows)

# select all a,b,c from t_distinct;
 a | b | c 
---+---+---
 1 | 2 | 3
 2 | 3 | 4
 3 | 4 | 5
 2 | 2 | 3
 3 | 3 | 4
 4 | 4 | 5
 5 | 6 |  
 5 | 6 |  
 6 | 7 |  
(9 rows)

  

2.返回 a,b,c 惟一值。(這裏NULL視爲相等)io

# select distinct a,b,c from t_distinct;
 a | b | c 
---+---+---
 2 | 2 | 3
 5 | 6 |  
 1 | 2 | 3
 6 | 7 |  
 3 | 3 | 4
 4 | 4 | 5
 3 | 4 | 5
 2 | 3 | 4
(8 rows)

  

3.返回a惟一的任意行table

# select distinct on (a) a,b,c from t_distinct;
 a | b | c 
---+---+---
 1 | 2 | 3
 2 | 2 | 3
 3 | 3 | 4
 4 | 4 | 5
 5 | 6 |  
 6 | 7 |  
(6 rows)

使用窗口函數能夠達到相似效果,可是能夠肯定返回哪行,所以也更慢一些:class

# select * from (select row_number() over (partition by a) as rn, * from t_distinct) t where rn=1;  
 rn | a | b | c 
----+---+---+---
  1 | 1 | 2 | 3
  1 | 2 | 2 | 3
  1 | 3 | 3 | 4
  1 | 4 | 4 | 5
  1 | 5 | 6 |  
  1 | 6 | 7 |  
(6 rows)

  

# select distinct on (a,b) a,b,c from t_distinct;
 a | b | c 
---+---+---
 1 | 2 | 3
 2 | 2 | 3
 2 | 3 | 4
 3 | 3 | 4
 3 | 4 | 5
 4 | 4 | 5
 5 | 6 |  
 6 | 7 |  
(8 rows)


#這裏NULL視爲相等
# select distinct on (c) a,b,c from t_distinct;
 a | b | c 
---+---+---
 1 | 2 | 3
 3 | 3 | 4
 3 | 4 | 5
 5 | 6 |  
(4 rows)
相關文章
相關標籤/搜索