2012-12-13 48 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`