Day06 MySQL的多表查询总练习

多表查询练习
根据需求,完成 SQL 语句的编写
1.查询员工的姓名、年龄、职位、部门信息。2.查询年龄小于30岁的员工姓名、年龄、职位、部门信息。
3.查询拥有员工的部门 ID 、部门名称。
4.查询所有年龄大于40岁的员工,及其归属的部门名称;如果员工没有分配部门,也需要展示出来。
5.查询所有员工的工资等级。
6.查询"研发部"所有员工的信息及工资等级。
7.查询"研发部"员工的平均工资。
8.查询工资比"灭绝"高的员工信息。
9.查询比平均薪资高的员工信息。
10.查询低于本部门平均工资的员工信息。
11.查询所有的部门信息,并统计部门的员工人数。
12.查询所有学生的选课情况,展示出学生名称,学号,课程名称

用到的表:

所有员工的信息表,emp表:

公司部门表,dept表:

薪资等级表,salaryGrade表:

学生信息,student表:

课程信息表,course表:

学生_课程表,是中间表,student_course表:

答案的代码:

#根据需求,完成 SQL 语句的编
#1.查询员工的姓名、年龄、职位、部门信息。
select  emp.name,age,job,dept.name from emp,dept where dept_id=dept.id;#隐式内连接

# 2.查询年龄小于30岁的员工姓名、年龄、职位、部门信息。
select  e.name,age,job,dept.name from emp e join dept on e.dept_id=dept.id where age<30;
select  e.name,age,job,dept.name from (select *from emp where age<30) e,dept where dept_id=dept.id; ##表子查询

#3.查询拥有员工的部门 ID 、部门名称。
 select  distinct d.id,d.name  from emp,dept d where d.id = emp.dept_id;
# select distinct  d.id,d.name from emp left join dept d on d.id = emp.dept_id;

#4.查询所有年龄大于40岁的员工,及其归属的部门名称;如果员工没有分配部门,也需要展示出来。
select  e.*,d.name from emp e left join dept d on d.id = e.dept_id where age>40
select e.*,dept.name from (select *from emp where age>40) e left join dept on dept_id=dept.id;

#5.查询所有员工的工资等级。
create table salaryGrade(
    grade char(1) comment'等级',
    lowest int comment '最低工资',
    higest int comment '最高工资'
)comment '工资等级表';
insert into salaryGrade(grade,lowest,higest) values('A',50000,100000),('B',10000,49999),('C',5000,10000),('D',0,5000);

select e.*,grade,lowest,higest from emp e,salaryGrade s where e.salary between lowest and higest;

#6.查询"研发部"所有员工的信息及工资等级。
#连接条件:emp.dept_id=dept.id,emp.salary between s.lowest and s,higest
#查询条件:dept.name="研发部"
select e.*,s.grade from emp e,dept d,salaryGrade s where e.dept_id=d.id and (e.salary between  s.lowest and s.higest) and d.name='研发部';

#7.查询"研发部"员工的平均工资。
select  avg(salary) from emp where dept_id=(select id from dept where name='研发部');

#8.查询工资比"员工a"高的员工信息。
select *from emp where salary>(select salary from emp where name='员工a');

#9.查询比平均薪资高的员工信息。
select *from emp where salary>(select avg(salary) from emp);

#10.查询低于本部门平均工资的员工信息。
#查询指定部门薪资:
select avg(e1.salary) from emp e1 where e1.dept_id=1;
#再查询每个部门低于平均薪资的员工
select *from emp e2 where salary<(select avg(e1.salary) from emp e1 where e1.dept_id=e2.dept_id);

#11.查询所有的部门信息,并统计部门的员工人数。
#先查询指定部门的员工人数
select count(*)from emp e where dept_id=1;
select d.id,d.name,(select count(*)from emp e where e.dept_id=d.id) '人数' from dept d;

#12.查询所有学生的选课情况,展示出学生名称,学号,课程名称
#连接条件:student.id=student_couse.studentid,course.id=student_couse.courseid
select s.name,s.studentno,c.name from student s,student_course sc,course c where sc.studentid=s.id and sc.courseid=c.id;

猜你喜欢

转载自blog.csdn.net/m0_67042480/article/details/128976622
今日推荐