首頁  >  文章  >  php教程  >  SQL中distinct的用法

SQL中distinct的用法

高洛峰
高洛峰原創
2016-12-13 09:25:502722瀏覽

在表中,可能會包含重複值。這並不成問題,不過,有時您也許希望僅僅列出不同(distinct)的值。關鍵字 distinct用於傳回唯一不同的值。

表A:

SQL中distinct的用法

表B:

SQL中distinct的用法

1.作用於單列

select distinct name from A1.作用於單列

select distinct name from A1.作用於單列

select distinct name from A

SQL中distinct的用法範例2.1

select distinct name, id from A

執行後結果如下:


實際上是根據name和id兩個欄位來去重的,這種方式Access和SQL Server同時支援。

SQL中distinct的用法範例2.2

select distinct xing, ming from B

回傳如下結果:


回傳的結果為兩行,這說明是「對字串」去重的,而是分別作用了xing和ming列。

SQL中distinct的用法3.COUNT統計

select count(distinct name) from A;  --表中name去重後的數目, SQL Server支持,而Access不支持

count是不能統計多個字段的,下面的SQL在SQL Server和Access中都無法運作。


select count(distinct name, id) from A;

若想使用,請使用巢狀查詢,如下:


select count(*) from (select distinct xing, name from B) AS M;

4.distinct必須放在開頭

select id, distinct name from A;   --會提示錯誤,因為distinct必須放在開頭

5.其他

distinct語句中指定的欄位只能是distinct的字段,其他字段是不可能出現的。例如,假如表A有「備註」列,如果想取得distinc name,以及對應的「備註」字段,想直接透過distinct是不可能實現的。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn