手机看片精品高清国产日韩,色先锋资源综合网,国产哺乳奶水91在线播放,乱伦小说亚洲色图欧洲电影

mysql去重的兩種方法詳解及實(shí)例代碼

2017-03-29 08:23:06 180

mysql去重的兩種方法詳解及實(shí)例代碼


這篇文章主要介紹了mysql去重的兩種方法詳解及?例代碼的相關(guān)資料,這里對(duì)去重的兩種方法進(jìn)行了一一實(shí)例詳解,需要的朋友可以參考下


mysql去重

方法一:     

在使用MySQL時(shí),有時(shí)需要查詢出某個(gè)字段不重復(fù)的記錄,雖然mysql提供 有distinct這個(gè)關(guān)鍵字來(lái)過(guò)濾掉多余的重復(fù)記錄只保留一條,但往往只用它來(lái)返回不重復(fù)記錄的條數(shù),而不是用它來(lái)返回不重記錄的所有值。其原因是 distinct只能返回它的目標(biāo)字段,而無(wú)法返回其它字段

下面先來(lái)看看例子:

table
id name
1 a
2 b
3 c
4 c
5 b

庫(kù)結(jié)構(gòu)大概這樣,這只是一個(gè)簡(jiǎn)單的例子,實(shí)際情況會(huì)復(fù)雜得多。

比如我想用一條語(yǔ)句查詢得到name不重復(fù)的所有數(shù)據(jù),那就必須使用distinct去掉多余的重復(fù)記錄。

select distinct name from table

得到的結(jié)果是:

name
 a
 b
 c

好像達(dá)到效果了,可是,我想要得到的是id值呢?改一下查詢語(yǔ)句吧:

select distinct name, id from table

結(jié)果會(huì)是:

id name
 1 a
 2 b
 3 c
 4 c
 5 b

distinct怎么沒(méi)起作用?作用是起了的,不過(guò)他同時(shí)作用了兩個(gè)字段,也就是必須得id與name都相同的才會(huì)被除。

我們?cè)俑母牟樵冋Z(yǔ)句:

select id, distinct name from table

很遺憾,除了錯(cuò)誤信息你什么也得不?,distinct必須放在開(kāi)頭。難到不能把distinct放到where條件里?能報(bào)錯(cuò)。

最終好用的語(yǔ)句如下:

select *, count(distinct name) from table group by name

結(jié)果:

id name count(distinct name)
1 a 1
2 b 1
3 c 1

最后一項(xiàng)是多余的,不用管就行了,目的達(dá)到。。。。。

哦,對(duì),再順便說(shuō)一句,group by 必須放在 order by 和 limit之前,不然會(huì)報(bào)錯(cuò)。。。。。。。。!OK了

總結(jié)語(yǔ)句:select *, count(distinct name) from (select * from table……等嵌套語(yǔ)句) 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

提交成功!非常感謝您的反饋,我們會(huì)繼續(xù)努力做到更好!

這條文檔是否有幫助解決問(wèn)題?

非常抱歉未能幫助到您。為了給您提供更好的服務(wù),我們很需要您進(jìn)一步的反饋信息:

在文檔使用中是否遇到以下問(wèn)題: