尚硅谷之MySQL基础
2、from型子查询
from型子查询即把内层sql语句查询的结果作为临时表供外层sql语句再次查询.
#from型 #找出比部门平均工资高的员工编号,基本工资 SELECT t_employee.eid,basic_salary FROM t_salary INNER JOIN t_employee INNER JOIN ( SELECT emp.dept_id AS did,AVG(s.basic_salary) AS avg_salary FROM t_employee AS emp,t_salary AS s WHERE emp.eid = s.eid GROUP BY emp.dept_id) AS temp ON t_salary.eid = t_employee.eid AND t_employee.dept_id = temp.did WHERE t_salary.basic_salary > temp.avg_salary; |
3、exists型子查询
#exists型 #查询部门信息,该部门必须有员工 SELECT * FROM t_department WHERE EXISTS (SELECT * FROM t_employee WHERE t_employee.dept_id = t_department.did); |
4、复制表子查询(了解)
(1)复制表
(1)拷贝表结构
CREATE TABLE newadmin LIKE admin;
(2)拷贝表结构和数据(但约束与索引除外)
CREATE TABLE newadmin AS ( SELECT * FROM admin ) ;
(3)拷贝表结构+数据
CREATE TABLE newadmin LIKE admin;
INSERT INTO newadmin SELECT * FROM admin;
(4)跨数据库拷贝表
CREATE TABLE newadmin LIKE shop.admin;
CREATE TABLE newshop.newadmin LIKE shop.admin;
(5)拷贝一个表中其中的一些字段(指定新名),其中一些数据
CREATE TABLE newadmin AS
(
SELECT id, username AS uname, password AS pass FROM admin WHERE id<10
) ;
(6)在创建表的同时定义表中的字段信息。
create table tt
(
eid int primary key auto_increment
)
as
(
select employee_id as eid,first_name,last_name,email from employees
);
(2)复制数据
在 INSERT 语句中加入子查询。
不必书写 VALUES 子句。
子查询中的值列表应与 INSERT 子句中的列名对应。
INSERT INTO emp2
SELECT * FROM employees WHERE department_id = 90;
或
INSERT INTO sales_reps(id, name, salary, commission_pct)
SELECT employee_id, last_name, salary, commission_pct
FROM employees
WHERE job_id LIKE '%REP%';