有如下数据:
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子句中的子查询
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子句中的子查询
from tb t
where not exists(select * from tb where t.id=id and t.times<times);
[征集]分组取最大N条记录方法征集,及散分....
form (
select *
from 有如下数据
order by id,times
) t
group by id
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函数。
order by 才是排序的,加desc 降序,不加升序
你要输出同类中最小的time 知道order by id times 即可
请各位看清楚帖子……
1.不能使用from子句的子查询
2.order by排序我也知道,但是order by无法在group by之前执行