mysql去重的兩種方法詳解及實例代碼
mysql去重
方法一:
在使用MySQL時,有時需要查詢出某個字段不重復的記錄,雖然mysql提供 有distinct這個關鍵字來過濾掉多余的重復記錄只保留一條,但往往只用它來返回不重復記錄的條數(shù),而不是用它來返回不重記錄的所有值。其原因是 distinct只能返回它的目標字段,而無法返回其它字段
下面先來看看例子:
table id name 1 a 2 b 3 c 4 c 5 b
庫結構大概這樣,這只是一個簡單的例子,實際情況會復雜得多。
比如我想用一條語句查詢得到name不重復的所有數(shù)據(jù),那就必須使用distinct去掉多余的重復記錄。
select distinct name from table
得到的結果是:
name a b c
好像達到效果了,可是,我想要得到的是id值呢?改一下查詢語句吧:
select distinct name, id from table
結果會是:
id name 1 a 2 b 3 c 4 c 5 b
distinct怎么沒起作用?作用是起了的,不過他同時作用了兩個字段,也就是必須得id與name都相同的才會被除。。。。。。。
我們再改改查詢語句:
select id, distinct name from table
很遺憾,除了錯誤信息你什么也得不到,distinct必須放在開頭。難到不能把distinct放到where條件里?能報錯。。。。。。。
最終好用的語句如下:
select *, count(distinct name) from table group by name
結果:
id name count(distinct name) 1 a 1 2 b 1 3 c 1
最后一項是多余的,不用管就行了,目的達到。。。。。
哦,對,再順便說一句,group by 必須放在 order by 和 limit之前,不然會報錯。。。。。。。。!OK了
總結語句:select *, count(distinct name) from (select * from table……等嵌套語句) group by name
方法二:
利用group by
SELECT * FROM( select * from customer where user=( SELECT source_user from customer WHERE user='admin') UNION ALL select * from customer where user=( select source_user from customer where user=( SELECT source_user from customer WHERE user='admin')) union ALL select * from customer where user=( select source_user from customer where user=( select source_user from customer where user=( SELECT source_user from customer WHERE user='admin'))) UNION ALL select * from customer where source_user=(/*我的上線的上線的user*/ select user from customer where user=( select source_user from customer where user=( SELECT source_user from customer WHERE user='admin'))) union all select * from customer where source_user=(/*我的上線的上線的上線user*/ select user from customer where user=( select source_user from customer where user=( select source_user from customer where user=( SELECT source_user from customer WHERE user='admin'))))) as alias group by user;
注意加別名,不然報錯,注意在where語句外面包裝一下,再用group by去重才會生效。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
詳解Mysql數(shù)據(jù)庫date, datetime類型設置0000-00-00默認值(default)報錯問題
這篇文章主要介紹了詳解Mysql數(shù)據(jù)庫date, datetime類型設置0000-00-00默認值(default)報錯問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01mysql啟動提示mysql.host 不存在,啟動失敗的解決方法
我將s9當眾原來的mysql4.0刪除后,重新裝了個mysql5.0,啟動過程中報一下錯誤,啟動失敗,查了一下群里面的老帖子也沒有個具體的明確說明2011-10-10Mysql中DATEDIFF函數(shù)的基礎語法及練習案例
Datediff函數(shù),最大的作用就是計算日期差,能計算兩個格式相同的日期之間的差值,下面這篇文章主要給大家介紹了關于Mysql中DATEDIFF函數(shù)的基礎語法及練習案例?的相關資料,需要的朋友可以參考下2022-09-09MySQL分頁Limit的優(yōu)化過程實戰(zhàn)
在mysql中進行分頁查詢時,一般會使用limit查詢,下面這篇文章主要給大家介紹了關于MySQL分頁Limit優(yōu)化的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧2018-09-09