SQL 中 distinct 的用法

在表中,可能會包含重複值。這並不成問題,不過,有時您也許但願僅僅列出不一樣(distinct)的值。關鍵詞 distinct用於返回惟一不一樣的值。mysql

表A:                                                                           表B:sql

                                    

1.做用於單列

select distinct name from A

執行後結果以下:spa

2.做用於多列

示例2.1

select distinct name, id from A

執行後結果以下:code

其實是根據name和id兩個字段來去重的,這種方式mySQL、Access和SQL Server同時支持。字符串

示例2.2

select distinct xing, ming from B

返回以下結果:select

返回的結果爲兩行,這說明distinct並不是是對xing和ming兩列「字符串拼接」後再去重的,而是分別做用於了xing和ming列。im

3.COUNT統計

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

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

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必須放在開頭
相關文章
相關標籤/搜索