MySQL在多个值上选择最大值?

时间:2012-12-13 00:05:46

标签: 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 个答案:

答案 0 :(得分: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上查看。

答案 1 :(得分: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`

答案 2 :(得分:0)

对于10以下的次要版本,无需加入:

SELECT file, MAX(CAST(CONCAT(Majorversion, '.', MinorVersion) AS DECIMAL(5,1))) as version
FROM my_table
group by file

结果:

file    version
a       3.0
b       1.1

次要版本> = 10将需要一些额外的格式:-)