方法一: mysql
在使用mysql時,有時須要查詢出某個字段不重複的記錄,雖然mysql提供 有distinct這個關鍵字來過濾掉多餘的重複記錄只保留一條,但每每只用它來返回不重複記錄的條數,而不是用它來返回不重記錄的全部值。其緣由是 distinct只能返回它的目標字段,而沒法返回其它字段sql
下面先來看看例子:spa
table
id name
1 a
2 b
3 c
4 c
5 b.net
庫結構大概這樣,這只是一個簡單的例子,實際狀況會複雜得多。orm
好比我想用一條語句查詢獲得name不重複的全部數據,那就必須使用distinct去掉多餘的重複記錄。blog
select distinct name from table
獲得的結果是:get
name
a
b
cit
好像達到效果了,但是,我想要獲得的是id值呢?改一下查詢語句吧:io
select distinct name, id from tabletable
結果會是:
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
[sql] view plaincopy
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去重纔會生效。