0

如何获取按最大列排序并按 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 始终正确,但其他字段不正确。

4

3 回答 3

0

看到这个:http ://bugs.mysql.com/bug.php?id=54784

于 2012-07-19T00:06:21.347 回答
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
于 2012-07-19T00:10:43.447 回答
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       
于 2012-07-19T00:55:21.297 回答