查找每行的最大值

时间:2011-06-11 22:00:45

标签: mysql

以下是我的问题的简化版本。有两个表有一台机器,第二个有关于它们的状态变化的信息与日期参考(不是实际的日期,而是移位索引,这就是为什么我必须进行另一个查询来获取日期本身)。 我想得到每台机器的最后状态 我的疑问是:

SELECT * FROM machines  
LEFT JOIN (SELECT * FROM statechange, dates WHERE....ORDER BY date DESC LIMIT 0,1) AS state
ON state.mid=machines.mid 

但是由于查询,我只得到一台机器。 如何在不创建视图的情况下执行此操作?

3 个答案:

答案 0 :(得分:2)

select m.*,s.`date` from machines as m
inner join (
select mid,`date`
from statechange
order by `date` desc) as s
on m.mid = s.mid
group by m.mid

答案 1 :(得分:1)

假设statechange表的主键是Max有意义的东西(如整数)

Select ...
From Machines As M
    Left Join   (
                Select S1.mid, Max( S1.PrimaryKeyCol ) As PrimaryKeyCol
                From statechange As S1
                    Join dates As D1
                        On D1.statechangeFK = S1.PrimaryKeyCol
                Where D1.date = (
                                Select Max( D2.date )
                                From dates As D2
                                Where D2.statechangeFK = D1.statechangeFK
                                )
                Group By S1.mid
                ) As LastStateChange
        On LastStateChange.mid = M.mid

    Left Join statechange As S
        On S.PrimaryKeyCol = LastStateChange.PrimaryKeyCol

最后一次连接是为了防止你从statechange表中返回列。


根据其他信息进行修订

Select ...
From Machines As M
    Left Join   (
                Select S1.mid, Max( S1.PrimaryKeyCol ) As PrimaryKeyCol
                From dates As D1
                    Join statechange As S1
                        On S1.DatesForeignKeyCol = D1.PrimaryKeyCol
                Where D1.date = (
                                Select Max( D2.date )
                                From dates As D2
                                    Join statechange As S2
                                        On S2.DatesForeignKeyCol = D2.PrimaryKeyCol
                                Where S2.mid = S1.mid
                                )
                Group By S1.mid
                ) As LastStateChange
        On LastStateChange.mid = M.mid

    Left Join statechange As S
        On S.PrimaryKeyCol = LastStateChange.PrimaryKeyCol

    Left Join dates As D
        On D.PrimaryKeyCol = S.DatesForeignKeyCol

我使用上述方法的原因之一是考虑到同一statechangemid值可能有多个date行的情况。上述方法将使用主键列作为该场景中的决胜局。

答案 2 :(得分:1)

通过这样做,您可以获得每台机器的最新状态更改。

SELECT mid, max(date)
FROM statechange
GROUP BY mid

然后你加入它来获得每台机器的当前状态。 (猜测列名。)

SELECT m.*, sc.state, sc.date
FROM machines m
INNER JOIN statechange sc 
    ON ( sc.mid = m.mid )
INNER JOIN (
            SELECT mid, MAX(date) date
            FROM statechange
            GROUP BY mid 
            ) s
    ON ( (s.mid = sc.mid) and (s.date = sc.date) );

我认为每台机器当前状态的视图可能会非常有用。