mysql distinct用法是什么

mysql distinct用法是什么

mysql中去重 distinct 用法

在使用mysql時,有時需要查詢出某個字段不重復的記錄,這時可以使用mysql提供的distinct這個關鍵字來過濾重復的記錄,但是實際中我們往往用distinct來返回不重復字段的條數(count(distinct id)),其原因是distinct只能返回他的目標字段,而無法返回其他字段,例如有如下表user:

mysql distinct用法是什么

用distinct來返回不重復的用戶名:select distinct name from user;,結果為:

mysql distinct用法是什么

這樣只把不重復的用戶名查詢出來了,但是用戶的id,并沒有被查詢出來:select distinct name,id from user;,這樣的結果為:

mysql distinct用法是什么

distinct name,id 這樣的mysql 會認為要過濾掉name和id兩個字段都重復的記錄,如果sql這樣寫:select id,distinct name from user,這樣mysql會報錯,因為distinct必須放在要查詢字段的開頭。

所以一般distinct用來查詢不重復記錄的條數。

如果要查詢不重復的記錄,有時候可以用group by :

select id,name from user group by name;

推薦教程: 《mysql教程

以上就是

? 版權聲明
THE END
喜歡就支持一下吧
點贊14 分享