选择所有最新的记录

时间:2011-03-09 13:27:18

标签: mysql group-by

我有这样的表结构

  sn  |  person_id  |   image_name |

   1  |   1         |      abc1.jpb 
   2  |   1         |      aa11.jpg  
   3  |   11        |      dsv.jpg
   4  |   11        |      dssd.jpg
   5  |   11        |      sdf.jpg

我需要不同的person_id最新行,如下所示

  2   |  1          |  aa11.jjpb
  5   |  11         |  sdf.jpg

可以吗?

3 个答案:

答案 0 :(得分:6)

SELECT * FROM table GROUP BY person_id HAVING MAX(sn)

修改

SELECT f.*
FROM (
      SELECT person_id, MAX(sn) as maxval
      FROM  table GROUP BY person_id
     ) AS x INNER JOIN table AS f
ON f.person_id = x.person_id AND f.sn = x.maxval;

其中table是你的表名。

答案 1 :(得分:5)

SELECT * FROM yourtable GROUP BY person_id ORDER BY sn DESC

基本上你想要从表中选择所有记录。然后它按person_id分组(将结果限制为每人id 1)...按SN降序排序意味着它将返回最近(最高)的sn

更新:(并已验证)

SELECT * FROM (SELECT * FROM stackoverflow ORDER BY sn DESC) a GROUP BY person_id ORDER BY sn

答案 2 :(得分:0)

SELECT * FROM table a WHERE a.`id` = ( SELECT MAX(`id`) FROM table b WHERE b.`person_id` = a.`person_id` );

您在括号内所做的是为具有该不同id的行选择最大person_id。因此,对于每个唯一的person_id,您将获得最新的条目。