mysql中select distinct的用法,mysqldistinct

來源:互聯網
上載者:User

mysql中select distinct的用法,mysqldistinct
在使用mysql時,有時需要查詢出某個欄位不重複的記錄,雖然mysql提供有distinct這個關鍵字來過濾掉多餘的重複記錄只保留一條,但往往只用它來返回不重複記錄的條數,而不是用它來返回不重記錄的所有值。其原因是distinct只能返回它的目標欄位,而無法返回其它欄位,經過實驗,有如下方法可以實現。

舉例如下:
這是test表的結構
id test1 test2
1 a 1
2 a 2
3 a 3
4 a 1
5 b 1
6 b 2
7 b 3
8 b 2
比如我想用一條語句查詢得到test1不重複的所有資料,那就必須使用distinct去掉多餘的重複記錄。
select distinct test1 from test
得到的結果是:
test1
a
b
好像達到效果了,可是,我想要得到的是id值?改一下查詢語句吧:
select distinct test1, id from test


test1 id
a 1
a 2
a 3
a 4
b 5
b 6
b 7
b 8
distinct怎麼沒起作用?作用是起了的,不過他同時作用了兩個欄位,也就是必須得id與test1都相同的才會被排除,這不可能的,id是自動成長的。。。

我們再改改查詢語句:

select id, distinct test1 from test
很遺憾,除了錯誤資訊你什麼也得不到,distinct必須放在開頭。難到不能把distinct放到where條件裡?能,照樣報錯。。。。。。。

通過查閱手冊,可以通過group_cancat來實現:
SELECT id, group_concat( DISTINCT test1 ) FROM test GROUP BY test1
id group_concat( distinct test1 )
1 a
5 b
不過它只有在4.1.0以後才能用,對於那些老版本的資料庫是不行的。


可以通過其他函數來實現:
select *, count(distinct test1) from test group by test1
id test1 test2 count( distinct test1 )
1 a 1 1
5 b 1 1
最後一項是多餘的,不用管就行了,目的達到。。。。。

還有更簡單的方法也可以實現:
select id, test1 from test group by test1
id test1
1 a
5 b

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.