一、单表查询
创建worker表
插入数据
1、显示所有职工的基本信息。
select * from worker;
2、查询所有职工所属部门的部门号,不显示重复的部门号。
select distinct 部门号 from worker;
3、求出所有职工的人数。
select count (职工号) from worker;
4、列出最高工资和最低工资。
select max(工资),min(工资) from worker;
5、列出职工的平均工资和总工资。
select avg(工资),sum(工资) from worker;
6、创建一个只有职工号、姓名和参加工作的新表,名为工作日期表。
create table 工作日期表 select 职工号,姓名 ,工作时间 from worker;
7、显示所有女职工的年龄。
select 2023-year(出生日期) from worker where 性别='女';
8、列出所有姓张的职工的职工号、姓名和出生日期。
select 职工号,姓名,出生日期 from worker where 姓名 regexp '^张';
9、列出1990年以前出生的职工的姓名、参加工作日期。
select 姓名,工作时间 from worker where year(出生日期)<1990;
10、列出工资在1000-5000之间的所有职工姓名。
select 姓名 from worker where 工资 between 1000 and 5000;
11、列出所有王姓和李姓的职工姓名。
select 姓名 from worker where 姓名 regexp '^[李,王]';
12、列出所有部门号为101的职工号、姓名、党员否。
select 职工号,姓名,政治面貌 from worker where 部门号 in(101);
13、将职工表worker中的职工按出生的先后顺序排序。
select 出生日期 from worker order by 出生日期;
14、显示工资最高的前3名职工的职工号和姓名。
select 职工号,姓名 from worker order by 工资 desc limit 3;
15、求出各部门党员的人数。
select 部门号,政治面貌, count(*) 人数 from worker where 政治面貌='党员' group by 部门号;
16、统计各部门的工资和平均工资
select 部门号, sum(工资) 总工资,avg(工资) 平均工资 from worker group by 部门号;
17、列出总人数大于4的部门号和总人数。
select 部门号,count(*) from worker group by 部门号 having count(*) >2;
二、多表查询
创建student表
创建score表
插入数据
1.查询student表的所有记录
select * from student;
2.查询student表的第2条到4条记录
select * from student limit 1,3;
3.从student表查询所有学生的学号(id)、姓名(name)和院系(department)的信息
select id,name,department from student;
4.从student表中查询计算机系和英语系的学生的信息
select id,name,department from student;
5.从student表中查询年龄30~40岁的学生信息
select * from student where 2023-birth between 30 and 40;
6.从student表中查询每个院系有多少人
select department,count(*) from student group by department;
7.从score表中查询每个科目的最高分
select c_name,max(grade) from score group by c_name;
8.查询李四的考试科目(c_name)和考试成绩(grade)
select st.name,sc.c_name,sc.c_name,sc.grade from student st join score sc on st.id=sc.stu_id where st.name='李四';
9.用连接的方式查询所有学生的信息和考试信息
select * from student left outer join score on student.id=score.stu_id;
10.计算每个学生的总成绩
select student.name,sum(score.grade) from student left outer join score on student.id=score.stu_id group by student.name;
11.计算每个考试科目的平均成绩
select c_name,avg(grade) from score group by c_name;
12.查询计算机成绩低于95的学生信息
select stu_id,grade from score where c_name= '计算机' and grade < 95;
13.查询同时参加计算机和英语考试的学生的信息
select sc.stu_id,group_concat(sc.c_name),st.name from score sc,student st where st.id=sc.stu_id group by sc.stu_id having group_concat(sc.c_name)='计算机,英语';
14.将计算机考试成绩按从高到低进行排序
select * from score where c_name='计算机' order by grade desc;
15.从student表和score表中查询出学生的学号,然后合并查询结果
select * from student st,score sc where st.id=sc.stu_id;
16.查询姓张或者姓王的同学的姓名、院系和考试科目及成绩
select * from student st,score sc where st.id=sc.stu_id and st.name regexp('^张|^王');
17.查询都是湖南的学生的姓名、年龄、院系和考试科目及成绩
select * from student st,score sc where st.id=sc.stu_id and st.address regexp('^湖南');