2012-12-13 52 views
3

我有一個表,如:MySQL在多個值上選擇最大值?

file MajorVersion MinorVersion 
a  0   1 
b  0   1 
a  0   2 
a  0   3 
b  1   0 
a  1   0 
b  1   1 

我想獲得每個文件的最新版本(最高主要版本最高的次要版本)。在這種情況下:

a 1 0 
b 1 1 

它似乎有可能有兩個連接和一組文件,但我認爲這可能是一個更好的辦法。也許通過使用?

回答

3

只有一個連接需要:

SELECT file, MajorVersion, MAX(MinorVersion) MinorVersion 
FROM  my_table NATURAL JOIN (
    SELECT file, MAX(MajorVersion) MajorVersion 
    FROM  my_table 
    GROUP BY file 
) t 
GROUP BY file 

看到它的sqlfiddle

+0

謝謝你,會是什麼,如果表中包含還需要其他領域的堆做到這一點的最好方法是什麼? – Myforwik

+0

@Myforwik:在這種情況下,最好引入第二次連接。 – eggyal

0

兩個連接的方法是:

select t1.* from `table` as t1 
JOIN 
(
    select `file` , max(`minor`) as `minor` from `table` 
    group by `file` , `major` 
) as t2 
on t1.`file` = t2.`file` and t1.`minor` = t2.`minor` and t1.`major` = t2.`major` 
JOIN 
(
select `file` , max(`major`) as `major` , `minor` from `table` 
group by `file` 
) as t3 
on t1.`file = t3.`file` and t1.`major` = t3.`major`