sql distinct 多列問題

2021-09-02 09:45:14 字數 567 閱讀 3756

查詢單列,使用select distinct name from photos;是沒有問題的。

但若想查詢多列,如select distinct name,nickname,department from photos;是將三列完全相同的內容過濾掉,但凡三列有一列不同,均會列出來。

若將distinct放後面,如select nickname,department,distinct name from photos;報錯,distinct必須放在開頭。將distinct放到where裡,也是報錯。

可以使用select *, count(distinct name) from photos group by name;最後一項是多餘的,不用管就行了,目的可以達到其中,group by 必須放在 order by 和 limit之前,不然會報錯。

或者可以使用select * from photos where id in (select max(id) from photos group by name),但是執行效率很低,能明顯感覺出資料庫的處理時間。 如果資料可以保證--隨著id遞增,資料越新,則使用此語句可查詢出最新結果。上面的語句則不保證。

SQL Distinct處理多列的問題

今天在做ssis的etl工作時,其中乙個left join元件的執行結果總是會多出一些記錄。分析了一下,該問題的原因是右表中作為關聯的那一列資料有重複。left join的執行策略可以理解為根據左表的每一條記錄的關聯欄位去對照右表的關聯字段,如果右表的關聯字段存在重複,就會生成重複的記錄。如果左表存...

sql DISTINCT 關鍵字去掉重複的列

distinct關鍵字主要用來從select語句的結果集中去掉重複的記錄。如果使用者沒有指定distinct關鍵字,那麼系統將返回所有符合條件的記錄組成結果集,其中包括重複的記錄。記錄一下工作中用到的sql語句吧,下面sql實現了去掉重複列id後顯示的資料。select distinct u.id,...

mysql drop 多列 MySQL多列分割槽

drop table if exists partition test create table partition test t id int 11 not null auto increment,test date datetime not null,t key varchar 16 test ...