【场景】:某一段数据

【分类】:限量查询、limit n,m

分析思路

难点:

1.每页3条,现在需要你取出第3页(页码从1开始)的人的信息,用到: limt m,n

2.统计求职方向为算法工程师且注册当天就完成了算法类试卷的人的信息和每次记录的得分,先求满足条件的用户,后用 left join 做连接查找信息和每次记录的得分

**(1)统计求职方向为算法工程师且注册当天就完成了算法类试卷的人 **

  • [使用]:job = '算法' and tag = '算法' and date(register_time) = date(submit_time)

(2)统计求职方向为算法工程师且注册当天就完成了算法类试卷的人的信息和每次记录的得分

  • [使用]:left join

(3)统计符合条件的用户参加过的所有考试最高得分排名,每页3条,现在需要你取出第3页(页码从1开始)的人的信息

  • [使用]:order by max_score desc limit 8,3;取出7-9

扩展:

前往查看:MySQL limit函数 限量查询

求解代码

方法一:

with子句 + 一步步拆解

with
    main as(
        #统计求职方向为算法工程师且注册当天就完成了算法类试卷的人
        select
            a.uid,
            level,
            register_time
        from user_info a,examination_info b,exam_record c
        where a.uid = c.uid and b.exam_id = c.exam_id
        and job = '算法'
        and tag = '算法' and date(register_time) = date(submit_time)
    )
    ,main1 as(
        #统计求职方向为算法工程师且注册当天就完成了算法类试卷的人的信息和每次记录的得分
        select
            uid,
            level,
            exam_id,
            start_time,
            register_time,
            submit_time,
            score
        from main
        left join exam_record using(uid)
    )

#统计符合条件的用户参加过的所有考试最高得分排名,每页3条,现在需要你取出第3页(页码从1开始)的人的信息
select
    uid,
    level,
    register_time,
    max(score) as max_score
from main1
group by uid
order by max_score desc
limit 6,3

方法二:

多表连接

select 
    a.uid,
    level,
    register_time,
    max(score) max_score
from exam_record a 
left join examination_info b using(exam_id) 
left join user_info c using(uid)
where tag='算法' and job ='算法' and date(start_time)= date(register_time)
group by uid having max_score is not null
order by max_score desc 
limit 6,3

缺少案例!这样写竟然也通过了

with
    main as(
        #统计求职方向为算法工程师且注册当天就完成了算法类试卷的人
        select
            a.uid,
            level,
            register_time
        from user_info a,examination_info b,exam_record c
        where a.uid = c.uid and b.exam_id = c.exam_id
        and job = '算法'
        and tag = '算法' and date(register_time) = date(submit_time)
    )
    ,main1 as(
        #统计求职方向为算法工程师且注册当天就完成了算法类试卷的人每次记录的得分等信息
        select
            uid,
            level,
            exam_id,
            start_time,
            register_time,
            submit_time,
            score
        from main
        left join exam_record using(uid)
    )

#统计符合条件的用户参加过的所有考试最高得分排名,每页3条,现在需要你取出第3页(页码从1开始)的人的信息
select
    uid,
    level,
    register_time,
    max(score) as max_score
from main1
group by uid,exam_id
order by max_score desc
limit 8,3