distinct的使用語法是這樣的:
select distinct expression[,expression...] from tables [where conditions];
在使用distinct的過程中主要注意一下幾點:
- 在對字段進行去重的時候,要保證distinct在所有字段的最前面
- 如果distinct關鍵字后面有多個字段時,則會對多個字段進行組合去重,只有多個字段組合起來的值是相等的才會被去重
下面我們通過在開發過程中經常遇到的一些關於distinct的實例來加深大家對該關鍵字用法的理解:
數據庫表結構和數據如下圖所示:

- 對單個字段進行去重sql:
select distinct age from user;
查詢結果
age
10
20
30
- 對多個字段進行去重sql:
select distinct name,age from user; 查詢結果 name age One 10 Zero 20 Two 20 Four 30 One 30
- 對多個字段進行去重並求count的sql(實際中我們往往用distinct來返回不重復字段的條數(count(distinct id)),其原因是distinct只能返回他的目標字段,而無法返回其他字段):
select count(distinct name,age) as total from user; 查詢結果 total 5
- 對select * 進行去重
select distinct * from user; 由於 * 代表所有字段,所以該sql和 select distinct id,name,age,sign from user 語義相同 查詢結果: id name age sign 1 One 10 夢想要有的,萬一實現了呢 2 Zero 20 http://www.chaoshizhushou.com 3 Two 20 OneZeroTwoFour 4 Four 30 加油 5 One 30 學習才是硬道理 6 Four 30 一日三省吾身
如果sql這樣寫:select id,distinct name from user,這樣mysql會報錯,因為distinct必須放在要查詢字段的開頭。
所以一般distinct用來查詢不重復記錄的條數。
如果要查詢不重復的記錄,有時候可以用group by :
select id,name from user group by name;
