oracle——distinct的用法

http://www.cnblogs.com/dogxuefeng/archive/2012/06/21/2557700.htmlhtml

distinct這個關鍵字來過濾掉多餘的重複記錄只保留一條,但每每只用 它來返回不重複記錄的條數,而不是用它來返回不重記錄的全部值。其緣由是distinct只有用二重循環查詢來解決,而這樣對於一個數據量很是大的站來講,無疑是會直接影響到效率的。htm

下面先來看看例子:blog

table表get

字段1     字段2    id        name    1           a    2           b    3           c    4           c    5           bit

庫結構大概這樣,這只是一個簡單的例子,實際狀況會複雜得多。table

好比我想用一條語句查詢獲得name不重複的全部數據,那就必須使用distinct去掉多餘的重複記錄。效率

select distinct name from table 獲得的結果是:select

---------- 循環

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以前,否則會報錯

相關文章
相關標籤/搜索