1. 程式人生 > 其它 >MySQL-sql99-exists後面的子查詢+案例講解

MySQL-sql99-exists後面的子查詢+案例講解

四、exists後面(相關子查詢)

其實就是一個bool型別

#四、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相同部門的員工姓名和工資

#查詢和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的員工在相同部門的員工的員工號和姓名

#查詢和姓名中包含字母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的部門工作的員工的員工號

#查詢在部門的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的員工姓名和工資

#查詢管理者是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顯示為一列,列名為姓.名

#查詢工資最高的員工的姓名,要求first_name和last_name顯示為一列,列名為姓.名
select concat(e.`first_name`,e.`last_name`) '姓.名'
from `employees` e
where e.`salary` =
(
	select max(`salary`)
	from `employees`
);