2014-03-01 43 views
1

這是我的sql小提琴。SQL通過將兩列分組來選擇最大值

http://sqlfiddle.com/#!2/7f0780/1/0

我似乎有,當我組兩列,以獲得最大()值,則返回錯誤相關的數據的問題。

你會看到id不正確。

有人可以幫我。

create table table1 (id int,id1 int, id2 int, version int); 
insert into table1 values 
(1,7,9,1), 
(2,7,9,2), 
(3,7,9,3), 
(4,7,9,4), 
(5,9,7,5), 
(6,9,7,6); 


SELECT max(version),id 
     FROM table1 
     group BY 
       id1,id2 



MAX(VERSION) ID 
4    1 
6    5 
+1

+1。 。 。你如何*不*起動一個問題,開始「這是我的SQL小提琴」,然後解釋什麼是問題? –

回答

1

你的SQL查詢:

SELECT max(version), id 
FROM table1 
group BY id1, id2 

請注意,您是由兩列編組。但是,您在select聲明中沒有選擇它們。相反,你有idid的值來自任意行,如MySQL documentation中所述。我的建議是永遠不要使用這個擴展,除非你真的很瞭解你在做什麼。

如果你想與最大值相關的ID,你可以使用not exists做到這一點:

select * 
from table1 t 
where not exists (select 1 
        from table1 t1 
        where t1.id1 = t.id1 and 
         t1.id2 = t.id2 and 
         t1.version > t.version 
       ); 

也就是說,從table1選擇的所有行版本的ID1/ID2對沒有較大的值。

編輯:

我要補充的是性能方面的原因,在table1(id1, id2, version)指數將有助於這個查詢了很多。

+0

不,'t1.version> t.version'是正確的:版本的較大值應該*不存在(對於id1,id2的這個組合) – wildplasser

相關問題