1.1 查询研发部门的所有员工信息
#步骤1: 查询研发部门的
did SELECT did FROM t_department WHERE dname = '研发部';
#步骤2: 嵌套子查询,查询员工信息
SELECT * FROM t_employee WHERE did = (SELECT did FROM t_department WHERE dname = '研发部');
1.1 查询和白露性别和部门相同信息的员工 #步骤1: 查询白露的性别和部门id (单行多列) 、
SELECT gender,did FROM t_employee WHERE ename = '白露';
#步骤2: 查询与之都相同的员工信息(in整体等于对比)
SELECT * FROM t_employee WHERE (gender,did) in (SELECT gender,did FROM t_employee WHERE ename = '白露'); #
行子对比的时候,可以使用in关键字,注意列要和值一一对应! 等同于多个列等于+and关系
in和or
a=in(1,2,3)
和
a=1 or a=2 or a=3
第一,in写着更简单
第二,当数据非常多的时候in的效率更高
# 1.1 查询和“白露”,“谢吉娜”同一部门的员工姓名和电话。
SELECT ename,tel,did FROM t_employee WHERE did IN(SELECT did FROM t_employee WHERE ename='白露' || ename='谢吉娜'); SELECT ename,tel,did FROM t_employee WHERE did =ANY(SELECT did FROM t_employee WHERE ename='白露' || ename='谢吉娜');
# 1.2 查询薪资比“白露”,“李诗雨”,“黄冰茹”三个人的薪资都要高的员工姓名和薪资。
SELECT ename,salary FROM t_employee WHERE salary >ALL(SELECT salary FROM t_employee WHERE ename IN('白露','李诗雨','黄冰茹'));
多个值,那么需要用in,not in, >all,>any....形式做比较!
All:对所有数据都满足条件才成立 ,例如:5>in(1,3,4);条件成立
Any:只要有一条数据满足条件就成立,例如,5>any(1,6,8,9);条件也成立,因为5>1
Some的作用和Any一样 。
update中嵌套子查询
4.3 update嵌套子查询
# 1.1 将“测试部”部门的员工薪资改为原来薪资的1.5倍。
# 步骤1: 查询测试部门对应的部门id
SELECT did FROM t_department WHERE dname = '测试部';
# 步骤2: 根据部门id修改员工的薪水
UPDATE t_employee SET salary = salary * 1.5 WHERE did = (SELECT did FROM t_department WHERE dname = '研发部');
# 1.2 将没有部门的员工的部门改为“测试部”部门。
# 步骤1: 查询测试部门对应的部门id
SELECT did FROM t_department WHERE dname = '测试部';
# 步骤2: 修改语句
UPDATE t_employee SET did = (SELECT did FROM t_department WHERE dname = '测试部')
WHERE did IS NULL;
# 1.3 修改“t_employee”表中“李冰冰”的薪资值等于“孙红梅”的薪资值。
# 步骤1: 查询孙红梅的薪资 [员工]
SELECT salary FROM t_employee WHERE ename = '孙红梅';
# 步骤2: 修改员工表的薪资 李冰冰 [员工]
UPDATE t_employee SET salary = (SELECT salary FROM t_employee WHERE ename = '孙红梅') WHERE ename = '李冰冰';
delete中嵌套子查询
# 1.1 将“测试部”部门的员工删除。
# 步骤1: 我们先根据部门名称查询部门id
SELECT did FROM t_department WHERE dname = '测试部'
# 步骤2: 在员工表中完成根据部门id删除员工数据
DELETE FROM t_employee WHERE did = (SELECT did FROM t_department WHERE dname = '测试部');
# 1.2 从“t_employee”表中删除和“李冰冰”同一个部门的员工记录。。
# 步骤1: 先查询李冰冰对应的部门编号
SELECT did FROM t_employee WHERE ename = '李冰冰'
# 步骤2: 删除李冰冰部门的其他员工
DELETE FROM t_employee WHERE did = (SELECT did FROM t_employee WHERE ename = '李冰冰');
# 完成和内层是同一个表! 双方占有同一个表的引用! mysql的保护机制,不让这么操作
DELETE FROM t_employee WHERE did = (SELECT did FROM ( SELECT did FROM t_employee WHERE ename = '李冰冰' ) temp );
# 4.5 insert嵌套子查询
#1.1 创建表(employee),复制某个表的结构(t_employee)
CREATE TABLE employee LIKE t_employee;
#1.2 使用INSERT语句+子查询,复制数据,此时INSERT不用写values
INSERT INTO employee (SELECT * FROM t_employee)
#1.3 同时复制表结构+数据 [创建表并复制数据]
CREATE TABLE employee1 AS (SELECT * FROM t_employee)