groupby查询分组后按条件查询所需要的记录
2017-07-19 14:21
357 查看
表结构
userlog
一、按userid分组 查询每个用户最新一条登录记录
1.
select a.* from userlog a,(select userid,max(logtime) logtime from userlog group by userid) b where a.userid = b.userid and a.logtime = b.logtime;
2.
select a.* from userlog a INNER JOIN(select userid,max(logtime) logtime from userlog group by userid) b ON a.userid = b.userid and a.logtime = b.logtime;
1和2在数据较少的情况下效率近似,数据量较大时建议使用2方式。
3.
select a.* from userlog a where not exists(select 1 from userlog where userid = a.userid and logtime > a.logtime);
4.
select a.* from userlog a where logtime = (select max(logtime) from userlog where userid = a.userid);
5.
select a.* from userlog a where 1 > (select count(*) from userlog where userid = a.userid and logtime > a.logtime );
1,2,3,4,5都属于带子查询的sql,其中1和2 是 关联子查询,先根据子查询查询出临时表,再根据表连接查询出对应的结果
3,4,5属于嵌套子查询 先在外部查询中取得一条记录的userid和logtime,然后执行子查询,条件就是子查询中的userid的值与外部刚才取到的值一样的所有记录的logtime字段的最大值,
也就是说对于外部的每一条记录都需要通过一次子查询,这严重影响了查询的效率
更多其他详细的查询 http://www.cnblogs.com/netserver/p/4518995.html
userlog
id | int |
userid | int |
logtime | timestamp |
1.
select a.* from userlog a,(select userid,max(logtime) logtime from userlog group by userid) b where a.userid = b.userid and a.logtime = b.logtime;
2.
select a.* from userlog a INNER JOIN(select userid,max(logtime) logtime from userlog group by userid) b ON a.userid = b.userid and a.logtime = b.logtime;
1和2在数据较少的情况下效率近似,数据量较大时建议使用2方式。
3.
select a.* from userlog a where not exists(select 1 from userlog where userid = a.userid and logtime > a.logtime);
4.
select a.* from userlog a where logtime = (select max(logtime) from userlog where userid = a.userid);
5.
select a.* from userlog a where 1 > (select count(*) from userlog where userid = a.userid and logtime > a.logtime );
1,2,3,4,5都属于带子查询的sql,其中1和2 是 关联子查询,先根据子查询查询出临时表,再根据表连接查询出对应的结果
3,4,5属于嵌套子查询 先在外部查询中取得一条记录的userid和logtime,然后执行子查询,条件就是子查询中的userid的值与外部刚才取到的值一样的所有记录的logtime字段的最大值,
也就是说对于外部的每一条记录都需要通过一次子查询,这严重影响了查询的效率
更多其他详细的查询 http://www.cnblogs.com/netserver/p/4518995.html
相关文章推荐
- 查询分组数据指行条件满足的行的上一条记录的技巧
- 工作中需要写一个shell用来查询符合条件的上下若干条记录!
- 【SQL】按字段分组查询符合条件记录的方法
- 记录一个mysql按日期分组统计的查询
- mysql分组查询获取组内某字段最大的记录
- sql分组后二次汇总(处理表重复记录查询和删除)的实现方法
- [MS SQL]SQL语句查询每个分组的前N条记录的实现方法
- MongoDB自增长主键,批量操作,distinct记录,条件组合查询
- sq更新语句条件子查询中有分组统计的sql,导致错误1093
- orcale 查询分组后的前n条记录
- 分组查询取最大时间记录的方法Oracle
- mysql 分组查询某一列最大的前10条记录
- select count(*) 查询满足条件的记录的条数
- SQL中分组函数的使用及前N条记录的查询方法
- MSSQL 查询分组前N条记录
- mysql查询分组后统计记录条数
- Oracle分组查询取每组排序后的前N条记录
- django orm多条件查询及except处理不存在记录的样码
- ContentResolver.query()分组查询通话记录
- SQL 单表多条记录分组查询分页代码