#四、exists后面(相关子查询) # 其实就是一个bool类型 select exists(select `employee_id` from `employees`)
判断exist后面有没有值
没有值的情况如下:
select exists(select `employee_id` from `employees` where `salary`=30000)
# 查询有员工的部门名 SELECT `department_name` FROM `departments` d WHERE EXISTS( SELECT * FROM `employees` e WHERE e.`department_id`=d.`department_id` );
也可以用in的方式
# 查询有员工的部门名 select `department_name` from `departments` d where d.`department_id` in( select `department_id` from `employees` )
# 查询没有女朋友的男神信息 select bo.* from `boys` bo where bo.`id` not in( select b.`boyfriend_id` from `beauty` b )
也可以用exists
# 查询没有女朋友的男神信息 select bo.* from `boys` bo where not exists( select b.`boyfriend_id` from `beauty` b where bo.`id`=b.`boyfriend_id` )
#查询和zlotkey相同部门的员工姓名和工资 select `last_name`,`salary` from `employees` where `department_id`=( select `department_id` from `employees` where `last_name`='zlotkey' );
#查询工资比公司平均工资高的员工的员工号,姓名和工资 SELECT `employee_id`,`last_name`,`salary` FROM `employees` WHERE `salary`>( SELECT AVG(`salary`) FROM `employees` );
#查询各部门中工资比本部门平均工资高的员工的员工号,姓名和工资 select e.`employee_id`,e.`last_name`,e.`salary`,e.`department_id` from `employees` e inner join ( select avg(`salary`) ag,`department_id` from `employees` group by `department_id` ) ag_dep on e.`department_id`=ag_dep.`department_id` where e.`salary`>ag_dep.ag 。 查询和姓名中包含字母u的员工在相同部门的员工的员工号和姓名 5.查询在部门的location_id为1700的部门工作的员工的员工号 6.查询管理者是King的员工姓名和工资 7.查询工资最高的员工的姓名,要求first_name和last_name显示为一列,列名为姓.名
#查询和姓名中包含字母u的员工在相同部门的员工的员工号和姓名 select e.`employee_id`,e.`last_name` from `employees` e where e.`department_id` in ( select distinct `department_id` from `employees` where `last_name` like '%u%' );
#查询在部门的location_id为1700的部门工作的员工的员工号 SELECT e.`employee_id` FROM `employees` e WHERE e.`department_id` IN ( SELECT `department_id` FROM `departments` WHERE `location_id` =1700 );
这一题 也可以用any来做
#查询在部门的location_id为1700的部门工作的员工的员工号 SELECT e.`employee_id` FROM `employees` e WHERE e.`department_id` =ANY ( SELECT `department_id` FROM `departments` WHERE `location_id` =1700 );
#查询管理者是K_ing的员工姓名和工资 select e.`last_name`,e.`salary` from `employees` e where e.`manager_id` =any ( select `employee_id` from `employees` where `last_name` ='K_ing' );
#查询工资最高的员工的姓名,要求first_name和last_name显示为一列,列名为姓.名 select concat(e.`first_name`,e.`last_name`) '姓.名' from `employees` e where e.`salary` = ( select max(`salary`) from `employees` );