有如下数据:
id       times    list
1 3 1
1 2 2
1 1 3
1 3 4
2 2 5
2 2 6
2 2 7我想查出相同id下,times最小的那条记录
用group by发现无法按照times排序,取出来的不是times最小的。不知道该如何写sql?
而且,不能在from字句中用子查询,因为我用hibernate,不支持from子句中的子查询

解决方案 »

  1.   

    select *
    from tb t
    where not exists(select * from tb where t.id=id and t.times<times);
      

  2.   

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

  3.   

    select *
    form (
    select *
    from 有如下数据
    order by id,times
    ) t
    group by id
      

  4.   


    127.0.0.1~root@localhost~test>select * from (select id,min(times) as times from ty group by id) a order by times ;
    +------+-------+
    | id   | times |
    +------+-------+
    |    1 |     1 |
    |    2 |     2 |
    +------+-------+
    2 rows in set (0.00 sec)127.0.0.1~root@localhost~test>select * from (select id,min(times) as times from ty group by id) a order by times desc ;
    +------+-------+
    | id   | times |
    +------+-------+
    |    2 |     2 |
    |    1 |     1 |
    +------+-------+
    2 rows in set (0.00 sec)127.0.0.1~root@localhost~test>
    用group by发现无法按照times排序,取出来的不是times最小的。
    不知道你的SQL是怎么写的,GROUP BY可以去到最小的times,用MIN函数。
      

  5.   

    group by 不是排序的,比如你用到一些函数,sum 等需要后面接group by 
    order by 才是排序的,加desc 降序,不加升序
    你要输出同类中最小的time 知道order by id times 即可
      

  6.   

    以上回答没有一个对的……
    请各位看清楚帖子……
    1.不能使用from子句的子查询
    2.order by排序我也知道,但是order by无法在group by之前执行
      

  7.   

    1.不能使用from子句的子查询把查询出来的插入到一个中间表,再到中间表去查,这样你的对象就能识别到了。