id   user   content
1    aaa     test
2    aaa     test1
3    bbb     test2
4    aaa     test3
5    ccc     test4
6    bbb     test5
7    bbb     test6
如上表,需要查询数据。常规写法是 select * from table order by id desc现有个需求,user字段,一个用户名只显示一条最新的。语句该如何写呀?

解决方案 »

  1.   

    select *
    from tb A
    where not exists (select 1 from tb where A.user=B.user and A.id>id)
      

  2.   

    mysql> select * from tt1 a where not exists (select 1 from tt1 where user=a.user and  a.id<id) group by user order by id;
    +------+------+---------+
    | id   | user | content |
    +------+------+---------+
    |    4 | aaa  | test3   |
    |    5 | ccc  | test4   |
    |    7 | bbb  | test6   |
    +------+------+---------+
    3 rows in set (0.00 sec)
    这样?
      

  3.   

    select * from table where id in (select max(id) from table group by user)
    请楼下斧正
      

  4.   

    select * from TB where id in (select max(id) from TB group by id)
      

  5.   

    参考下贴中的多种方法http://topic.csdn.net/u/20091231/16/2f268740-391e-40f2-a15e-f243b2c925ab.html
    [征集]分组取最大N条记录方法征集,及散分....