MySQL组按降序排列

时间:2014-08-10 12:07:03

标签: mysql group-by

我有一个不包含唯一列的表

id | fid | ver | dir

1 || 1 || 1 || 3

2 || 2 || 1 || 2

3 || 3 || 1 || 3

4 || 3 || 2 || 3

5 || 4 || 1 || 4

6 || 5 || 1 || 5

我的问题是如何在dir = 3

中选择最新fid的ID(基于ver)

我尝试了(SELECT id FROMWHERE目录='3' GROUP BY fid ORDER BY版本),但它给了我

id

1

3

这不是我想得到的结果。这是我期望得到的结果:

id

1

4

3 个答案:

答案 0 :(得分:0)

SELECT MAX(id) FROM table WHERE dir = '3' GROUP BY fid ORDER BY version

答案 1 :(得分:0)

尝试按版本分组,

SELECT id FROM table WHERE dir='3' GROUP BY version

答案 2 :(得分:0)

select id
from myTable t1
where dir = 3
and not exists (
    select 1
    from myTable t2
    where t1.version < t2.version
    and t1.dir = t2.dir
    and t1.fid = t2.fid
)
order by version
相关问题