mysql 子查询案例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 子查询案例相关的知识,希望对你有一定的参考价值。
#查询和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 employee_id,last_name,salary
FROM (
SELECT AVG(salary) s,department_id
FROM employees
GROUP BY department_id
) a
INNER JOIN employees e
ON a.department_id=e.department_id
WHERE e.salary>s;
#查询和姓名中包含字母u的员工在相同部门的员工的员工号和姓名
先查询包含u员工的部门id,再查id相同情况
SELECT employee_id,last_name
FROM employees
WHERE department_id IN(
SELECT DISTINCT department_id
FROM employees
WHERE last_name LIKE ‘%u%‘
);
#查询在部门的location_id为1700的部门工作的员工的员工号
注先查询location_id等于1700的部门编号,在查询员工号
SELECT employee_id
FROM employees e
WHERE e.`department_id` IN(
SELECT department_id
FROM departments d
WHERE d.`location_id`=1700
)
#查询管理者是K_ing的员工姓名和工资,有两个K_ing
SELECT last_name,salary
FROM employees e
WHERE e.manager_id IN(
SELECT `employee_id`
FROM employees m
WHERE `last_name`=‘K_ing‘
);
#查询工资最高的员工的姓名,要求first_ame和last_name 显示为一列,列名为 姓.名
#起别名有特殊字符需要用引号括起来
SELECT CONCAT(first_name,last_name) ‘姓.名‘
FROM employees e
WHERE e.salary=(
SELECT MAX(salary)
FROM employees
);
以上是关于mysql 子查询案例的主要内容,如果未能解决你的问题,请参考以下文章