子查询:一个select语句中包含另一个select语句,其中第二个select语句可以跟在where或者from后面。
where后:把select后的结果当作另一个select的条件值;
from后:把查询的结果当作一个新的表
数据准备:
薪水等级表:
create table salaryClass(
grade tinyint,
lowsalary int,
highsalary int
);
insert into salaryClass
values
(1,700,1200),
(2,1300,2000),
(3,2100,3000),
(4,3100,4000),
(5,4000,5000)
部门信息表:
create table department(
d_no int,
d_name varchar(10),
d_local varchar(10)
);
insert into department
values
(10,'财务部','上海'),
(20,'人力部','北京'),
(30,'销售部','天津'),
(40,'后勤部','重庆'),
(50,'生产部','成都')
员工信息表:
create table employee(
e_no int,
e_name varchar(10),
d_no int,
salary float
);
insert into employee
values
(1001,'张三',10,800.0),
(1002,'李四',20,1000.0),
(1003,'王五',30,1600.0),
(1004,'赵六',40,2000.0),
(1005,'田七',50,2500.0),
(1006,'康八',20,3500.0),
(1001,'张飞',10,850.0),
(1007,'关羽',20,1050.0),
(1008,'刘备',30,1650.0),
(1009,'诸葛亮',40,2050.0),
(1010,'曹操',50,2550.0)
例子:查询和关羽同一个部门的员工;
第一步:得到关羽的部门编号:
select d_no from employee
where e_name = '关羽';
#结果是20;
第二步:得到部门编号是20的员工名称:
select e_name from employee
where d_no = 20;
# 李四
康八
关羽
整合第一、二步:
select e_name from employee
where d_no = (
select d_no from employee
where e_name = '关羽'
);
例子:查询和30号部门的员工工资大于1550的人名;
第一步:得到部门编号是30的所有人的工资以及人名:
select e_name,salary from employee
where d_no = 30;
王五 1600
刘备 1650
第二步:在第一步的得到的结果基础上筛选出工资大于1550的人;
select e_name from
(select e_name,salary from employee
where d_no = 30) as tmp_e
where tmp_e.salary > 1550;
例子:查询比关羽的薪资高的人的信息;
select * from employee
where salary > (select salary from employee where e_name = '关羽');
多表例子:查询员工编号是1004的员工姓名,工作点,工资等级;
select e_name,d_local,grade from employee,department,salaryClass
where employee.e_no = 1004 and
employee.d_no = department.d_no and
salaryClass.lowsalary <= employee.salary and salaryClass.highsalary >= employee.salary
来源:CSDN
作者:CF_S
链接:https://blog.csdn.net/shen_chengfeng/article/details/103655992