时间:2021-07-01 10:21:17 帮助过:7人阅读
有什么办法可以查询出group by的分组中,每组内的排序中最大或最小的一行数据?
想到用group by 但它只能显示第一条,而不能显示最新一条,
想加个order by time desc,可是orber by只能加在group by后面。
有什么办法可以查询出group by的分组中,每组内的排序中最大或最小的一行数据?
方案一: 通过同表子查询或联查找到最大的数据ID
select * from track where id in(select max(id) from track group by target_id);
or
select * from track where id in(select substring_index(group_concat(id order by id desc),',',1) as maxid from track group by target_id);
方案二:分两步查询,php中先查询最大ID,再通过ID数组查询列表数据
select a.* from(select max(id) as id from info group by userid) b left join info a on a.id=b.id
把查询结果存起来,再取
使用order by
select * from (
select (@mycnt := @mycnt + 1) as ROWNUM,name,age
from tb where AGe < 20 order by name,age
) as A where ROWNUM = 1
只懂SqlServer,这个是仿照SqlServer写法的,可以试试
SELECT a.id, a.user_id, a.info, a.create_time
FROM (SELECT id, user_id, info, create_time FROM tbl_user
ORDER BY user_id, create_time DESC, id DESC) a
GROUP BY a.user_id