在数据库中选择最新版本的行

时间:2012-10-05 20:04:32

标签: mysql sql

这是场景......

我有一个MySQL表(称为灯具),其中包含以下内容....

enter image description here

您可以看到2012-06-01日团队A的灯具已更新,版本4是​​最后一个启动时间为12:00的条目。

我需要一些SQL来选择2012-06-01日期的所有记录,但只选择最新的版本,所以看起来应该是....

enter image description here

这是我尝试过的,它看起来很完美但是它返回了错误的ID和时间(这是改变的),见下文......

 select id, max(version), team, date, time, oppo from fixtures where date = "2012-06-01" group by team

enter image description here

3 个答案:

答案 0 :(得分:1)

select id,version, team, date, time, oppo 
from fixtures A where id in
(
    select max(id)from fixtures 
    where date = "2012-06-01" 
    group by team
)

假设:id是主键

答案 1 :(得分:0)

试试这个:

select f.id, a.version, a.team, f.date, f.time, f.oppo from fixtures f inner join
(select max(version) version, team from fixtures where date = "2012-06-01" group by team) a
 on f.version = a.version and f.team = a.team

答案 2 :(得分:0)

SELECT id
    ,version
    ,team
    ,DATE
    ,TIME
    ,oppo
FROM fixtures
WHERE DATE = "2012-06-01"
    AND id = (
        SELECT max(f2.id)
        FROM fixtures f2
        WHERE f2.DATE = DATE
            AND f2.team = team
        )