MySQL:MAX没有返回

时间:2012-07-19 00:03:03

标签: mysql

如何获取按最大列排序并按ID分组的行列表?我不断获得正确的最大值,但其他字段是从其他行获得的。

我使用以下内容:

SELECT p.*
            FROM `logs` AS p
            JOIN
            (SELECT person_id,
             MAX(`datetime`) AS datetime
             FROM `logs`
             GROUP BY `person_id`
             ) AS pg
             ON  pg.person_id = p.person_id
             AND pg.`datetime` = p.datetime
             group by person_id

我的查询在哪里错了?日期时间和人员ID始终是正确的,但其他字段不是。

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

  

SELECT MIN(datetime)并不总是返回最小日期时间   值。与MAX相同。

临时解决方法:

        SELECT p.*
        FROM   `logs` AS p
        JOIN
              (SELECT person_id,
                      MAX(CAST(`datetime` as CHAR(25))) AS `datetime`
               FROM `logs`
               GROUP BY `person_id`
               ) AS pg
                   ON  pg.person_id = p.person_id AND
              pg.`datetime` = p.datetime
         group by person_id

答案 2 :(得分:0)

请尝试以下方法:

SELECT logs.* 
  FROM ( SELECT person_id,
             MAX(`datetime`) AS latest
             FROM `logs` 
         GROUP BY person_id) AS dt
INNER
  JOIN logs 
    ON logs.person_id= dt.person_id
   AND logs.datetime= dt.latest