舉比例如以下:
這是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
