这是我的photo表的结构
 CREATE TABLE `photo` (                                                               
          `id` bigint(20) NOT NULL,                                                          
          `uptime` datetime default NULL,                                                    
          `user_id` bigint(20) NOT NULL,                                                     
           PRIMARY KEY  (`id`),                                                               
          KEY `FK65B3E3248CE7A33` (`user_id`),                                                         CONSTRAINT `FK65B3E3248CE7A33` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),   
         
        )  我想从photo表中找到 以userid分组的,且上传时间最晚的记录
也就是查出来每个user 最新上传的photo

解决方案 »

  1.   

    select photo.*
    from photo,(select user_id,max(uptime) as max_uptime from photo group by user_id) p
    where photo.user_id=p.user_id 
    and photo.uptime=p.max_uptime
      

  2.   

    我查出来的结果虽然按user分组了,但是 不是最新的那条记录
      

  3.   

    不会啊,一楼的应该是uptime 最大的那条啊。
      

  4.   

    或者你也可以用inner join 这种格式,结果应该是一样
    select photo.*
    from photo inner join (select user_id,max(uptime) as max_uptime from photo group by user_id) p
    on photo.user_id=p.user_id and photo.uptime=p.max_uptime
      

  5.   

    如果数据不多的话,也可以直接
    select * 
    from photo a
    where not exists (select 1 from photo where user_id=a.user_id and uptime>a.uptime)
      

  6.   

    贴出数据来看看 是不是你的数据有问题max(datetime)能查出最大记录
      

  7.   

    谢谢善良的你,我试了下会有重复,而且,DISTINCT去不掉
      

  8.   

    贴记录及要求结果出来看看
    select a.id,a.uptime,a.user_id from photo a
    left join photo b on a.userid=b.userid and a.uptime<=b.uptime
    group by a.id,a.uptime,a.user_id having count(b.id)=1
      

  9.   

    看你的表结构,应该你的photo表类似一个日志表,所以,上传时间最晚的记录也就是ID值最大的记录:写法1:
    select a.*,b.* from photo a,`user` b  where a.user_id=b.id and not exists (
    select 1 from photo c where c.user_id=a.user_id and c.id>a.id);写法2:
    select a.*,b.* from photo a,`user` b  where a.user_id=b.id and a.id=(select max(c.id) from  photo c where c.user_id=a.user_id);写法3:
    select a.*,b.* from photo a,`user` b,(select user_id,max(id) as newid from  photo group by user_id) c where a.user_id=b.id and a.id=c.newid;