MySQL刷题之路总结~

13 阅读3分钟

你们好,我是金金金。

image.png

基础查询

简单处理查询结果

查询结果去重

题目

image.png

答案

-- 使用 group by 分组语句
select university from user_profile group by university

-- 使用 distinct 关键词
select distinct from user_profile

区别

  1. distinct:适合当你只需要知道某列中的不同值时。它很简单,但是功能有限,无法直接获取其他相关信息。
  2. group by:更适合当你需要基于某个字段进行分组,并希望同时获取该组内的其他信息或进行一些计算时。它的功能更强大,适用于更多样化的查询需求

思路

  1. 首先查找出所有记录的的学校字段数据
  2. 然后利用关键词进行分组/过滤即可

查询结果限制返回行数

题目

image.png

答案

-- 使用 limit 关键词
select device_id from user_profile limit 2

select device_id from user_profile limit 0,2

思路

  1. 首先查出所有的数据
  2. 使用limit关键词进行限制返回条数即可

将查询后的列重新命名

题目

image.png

答案

-- 使用 as 关键词 重命名
select device_id as user_infos_example from user_profile limit 2

思路

  1. 首先查找出所有数据 接着 利用limit关键词只返回前面两条数据
  2. 然后利用as关键词对列名进行重命名

条件查询

基础排序

查找后排序

题目

image.png

答案

-- 使用 order by 排序语句(不写默认是ASC 升序,DESC则是降序)
select device_id, age from user_profile order by age ASC

思路

  1. 首先查出所有的device_idage字段
  2. 利用order byage进行排序即可

查找后多列排序

题目

image.png

答案

-- 使用 order by 排序语句 可以设定多个字段排序
select device_id, gpa, age from user_profile order by gpa asc, age asc

思路

  1. 首先查出所有的device_idgpaage字段
  2. 利用order by对多个字段依次排序即可

查找后降序排列

题目

image.png

答案

-- 使用 order by 即可
select device_id, gpa, age from user_profile order by gpa desc, age desc

思路

  1. 首先查出所有的device_idgpaage字段
  2. 利用order by对多个字段依次排序即可

注意desc不能省略,必须显性填写

基础操作符

查找学校是北大的学生信息

题目

image.png

答案

-- 使用 `where` 子句进行筛选
select
    device_id,
    university
from
    user_profile
where
    university = '北京大学'

思路

  1. 首先查出device_iduniversity列数据
  2. 使用 where 子句进行筛选出university为北京大学的数据

查找年龄大于24岁的用户信息

题目

image.png

答案

-- 使用 `where` 子句进行筛选
select
    device_id,
    gender,
    age,
    university
from
    user_profile
where
    age > 24

思路

  1. 首先查出device_idgenderageuniversity列数据
  2. 使用 where 子句筛选出age大于24的数据

综合练习

21年8月份练题总数

题目

image.png

答案

select 
    count(distinct device_id) as did_cnt, 
    count(*) as question_cnt
from
    question_practice_detail
where
    date between '2021-08-01' and '2021-08-31'

思路

  1. 首先把两个需要返回的字段定义好
  2. where条件查出2021年8月份区间的数据
  3. 利用distinct对总用户数进行去重过滤
  4. 利用count计数练习题目的总次数即可
  • 编写有误还请大佬指正,万分感谢。