表结构如下<table>
<tr><th>id</th><th>client_id</th><th>info</th><th>addtime</th></tr>
<tr><td>1</td><td>1</td><th>message1</td><th>2012-01-01 00:00:00</td></tr>
<tr><td>2</td><td>2</td><th>message2</td><th>2012-01-01 00:00:02</td></tr>
<tr><td>3</td><td>3</td><th>message22</td><th>2012-01-01 00:00:03</td></tr>
<tr><td>4</td><td>4</td><th>message32</td><th>2012-01-01 00:00:08</td></tr>
<tr><td>5</td><td>1</td><th>message4442</td><th>2012-01-01 00:00:10</td></tr>
<tr><td>6</td><td>2</td><th>message55</td><th>2012-01-01 00:00:19</td></tr>
<tr><td>7</td><td>3</td><th>message621</td><th>2012-01-01 00:00:30</td></tr>
<tr><td>8</td><td>4</td><th>message8o98</td><th>2012-01-01 00:00:55</td></tr>
</table>按client_id分组,查询每组里的最新一条

解决方案 »

  1.   

    再贴下表结构和内容
    id   client_id   info             addtime 
    1    1           message1         2012-01-01 00:00:00  
    2    2           message2         2012-01-01 00:00:02  
    3    3           message22        2012-01-01 00:00:03  
    4    4           message32        2012-01-01 00:00:08  
    5    1           message4442      2012-01-01 00:00:10  
    6    2           message55        2012-01-01 00:00:19  
    7    3           message621       2012-01-01 00:00:30  
    8    4           message8o98      2012-01-01 00:00:55  
      

  2.   

    select * from tt a where not exists(select 1 from tt where a.client_id=client_id
    and cdate(a.info & a.addtime)<cdate(info & addtime)
    )
      

  3.   

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

  4.   

    总结了一下:
    方案1:SELECT * FROM (SELECT * FROM client_status ORDER BY addtime DESC )a GROUP BY client_id
    explain分析id select_type table type possible_keys key key_len ref rows Extra
    1  PRIMARY  <derived2>  ALL  NULL  NULL  NULL  NULL  9  Using temporary; Using filesort
    2  DERIVED  client_status  ALL  NULL  NULL  NULL  NULL  9  Using filesort
    方案2:SELECT * FROM client_status a WHERE NOT EXISTS (SELECT 1 FROM lient_status WHERE a.client_id = client_id AND a.addtime < addtime)explain分析id select_type table type possible_keys key key_len ref rows Extra
    1  PRIMARY  a  ALL  NULL  NULL  NULL  NULL  9  Using where
    2  DEPENDENT SUBQUERY  client_status  ref  client_id  client_id  3  pdmon.a.client_id  1  Using where
    方案3:SELECT * FROM `client_status` WHERE addtime IN (SELECT max( addtime ) FROM client_status GROUP BY client_id )explain分析id select_type table type possible_keys key key_len ref rows Extra
    1  PRIMARY  client_status  ALL  NULL  NULL  NULL  NULL  9  Using where
    2  DEPENDENT SUBQUERY  client_status  index  NULL  client_id  3  NULL  1   如果看不清,可以移步这里:http://www.cnblogs.com/mybest/archive/2012/03/26/2418200.html
    如果有更高效的SQL,请继续跟贴
      

  5.   

    id client_id info addtime  
    select * from table_name group by client_id order by addtime desc