本文基于前段时间学习总结的 MySQL 相关的查询语法,在牛客网找了相应的 MySQL 题目进行练习,以便加强对于 MySQL 查询语法的理解和应用。
以下内容是牛客题霸-SQL入门篇前 20 道题目的 MySQL 代码答案。
一、示例所使用的数据库表(名称都为 user_profile)
1.1 表一
1.2 表二
1.3 表三
1.4 表四
二、SQL 题目
SQL 1:查询用户信息表中所有的数据
select * from user_profile
SQL 2:查询用户的设备 id,性别,年龄,学校信息
select device_id, gender, age, university
from user_profile
SQL 3:查询用户来自学校的去重数据
select distinct university from user_profile
SQL 4:查询前 2 个用户的设备 id 信息
select device_id from user_profile
limit 2
SQL 5:查询前 2 个用户明细设备 id 数据,并将列名改为 ‘user_infos_example’
select device_id as user_infos_example
from user_profile
limit 2
SQL 6:查询所有北京大学学生的设备 id ,学校信息
select device_id, university from user_profile
where university = '北京大学'
SQL 7:查询年龄大于 24 岁的用户的设备 id、性别、年龄、学校信息
select device_id, gender, age, university
from user_profile
where age > 24
SQL 8:查询 20 岁及以上且23岁及以下的用户的设备 id,性别,年龄信息
select device_id, gender, age
from user_profile
where age between 20 and 23
SQL 9:查询除复旦大学的所有用户信息
select device_id, gender, age, university
from user_profile
where university <> '复旦大学'
SQL 10:查询所有年龄不为空的用户的设备 id,性别,年龄,学校信息
select device_id, gender, age, university
from user_profile
where age is not null
SQL 11:查询是男性且 GPA 在 3.5 以上(不包括 3.5)的用户信息
select device_id, gender, age, university, gpa
from user_profile
where gender = 'male' and gpa > 3.5
SQL 12:查询学校为北大或 GPA 在 3.7 以上(不包括 3.7)的用户信息
select device_id, gender, age, university, gpa
from user_profile
where university = '北京大学' or gpa > 3.7
SQL 13:查询学校为北大、复旦和山大的用户信息
select device_id, gender, age, university, gpa
from user_profile
where university in('北京大学', '复旦大学', '山东大学')
SQL 14:查询 GPA 在 3.5 以上(不包括 3.5)的山东大学用户信息或 GPA 在 3.8 以上(不包括 3.8)的复旦大学用户信息
select device_id, gender, age, university, gpa
from user_profile
where gpa > 3.5 and university = '山东大学'
or gpa > 3.8 and university = '复旦大学'
SQL 15:查询所有大学中带有北京的用户的设备 id,年龄,大学信息
select device_id, age, university from user_profile
where university like '%北京%'
SQL 16:查询复旦大学学生的最高 GPA 是多少
select gpa from user_profile
where university = '复旦大学'
order by gpa desc
limit 1
SQL 17:查询男性用户有多少人及其平均 GPA
select count(*) as male_num, avg(gpa) as avg_gpa
from user_profile
where gender = 'male'
SQL 18:查询每个学校每种性别的用户数,30天内平均活跃天数,平均发帖数量
select gender, university, count(*) as user_num,
avg(active_days_within_30) as avg_active_day,
avg(question_cnt) as avg_question_cnt
from user_profile
group by university, gender
SQL 19:查询平均发贴数 < 5 的学校或平均回帖数 < 20 的学校
select university, avg(question_cnt) as avg_question_cnt,
avg(answer_cnt) as avg_answer_cnt
from user_profile
group by university
having avg_question_cnt < 5 or avg_answer_cnt < 20
SQL 20:查询不同大学的用户平均发帖情况,并按照平均发帖数量进行升序排列
select university, avg(question_cnt) as avg_question_cnt
from user_profile
group by university
order by avg_question_cnt