mysql为每个关系选择最高记录

时间:2012-05-25 15:14:59

标签: mysql

我有一张包含以下数据的表格:

=========================================
| name        |  version   | project_id |
=========================================
| foo         |           1|           1|
| new foo     |           2|           1|
| bar         |           1|           2|
=========================================

如何编写返回每个产品的最高版本记录的查询?从上表中,我想得到以下结果:

=========================================
| name        |  version   | project_id |
=========================================
| new foo     |           2|           1|
| bar         |           1|           2|
=========================================           

3 个答案:

答案 0 :(得分:4)

测试表

enter image description here

查询

enter image description here

结果

enter image description here

赢得我的朋友:)

答案 1 :(得分:1)

SELECT
  t1.name, t1.version, t1.project_id
FROM
  tablename t1
JOIN
  (SELECT max(version) as version, project_id FROM tablename GROUP BY project_id) t2
ON t1.project_id = t2.project_id AND t1.version = t2.version

答案 2 :(得分:0)

最简单的方法如下所示

select substring_index(group_concat(`name` order by version),',',-1) as `name`,
max(version) as version,project_id 
from your_table 
group by project_id 
order by projec`t_id;