子查询
某些情况下,当进行一个查询时,需要的条件或数据要用另外一个 select 语句的结果,这个时候,就要用到子查询。
例如:
为了给主查询(外部查询)提供数据而首先执行的查询(内部查询)被叫做子查询。
一般根据子查询的嵌入位置分为,where型子查询,from型子查询,exists型子查询。1、where型子查询
where型子查询即把内层sql语句查询的结果作为外层sql查询的条件.
IN:等于任何一个 ALL:和子查询返回的所有值比较。例如:sal>ALL(1,2,3)等价于sal>1 && sal>2 && sal>3,即大于所有。 ANY:和子查询返回的任意一个值比较。例如:sal>ANY(1,2,3)等价于sal>1 or sal>2 or sal>3,即大于任意一个就可以。 EXISTS:判断子查询是否有返回结果(不关心具体行数和内容),如果返回则为TRUE,否则为FALSE。 |
#子查询#where型子查询#查询比“小红”的工资高的员工编号SELECT * FROM t_salaryWHERE basic_salary > (SELECT basic_salary FROM t_employee INNER JOIN t_salary ON t_employee.eid=t_salary.eid WHERE t_employee.ename=’小红’);#查询和小红,小李在同一个部门的员工SELECT * FROM t_employeeWHERE dept_id IN(SELECT dept_id FROM t_employee WHERE ename=’小红’ OR ename = ‘小李’);SELECT * FROM t_employeeWHERE dept_id = ANY(SELECT dept_id FROM t_employee WHERE ename=’小红’ OR ename = ‘小李’);#查询全公司工资最高的员工编号,基本工资SELECT eid,basic_salary FROM t_salaryWHERE basic_salary = (SELECT MAX(basic_salary) FROM t_salary);SELECT eid,basic_salary FROM t_salaryWHERE basic_salary >= ALL(SELECT basic_salary FROM t_salary); |
2、from型子查询
from型子查询即把内层sql语句查询的结果作为临时表供外层sql语句再次查询.
#from型#找出比部门平均工资高的员工编号,基本工资SELECT t_employee.eid,basic_salaryFROM t_salary INNER JOIN t_employee INNER JOIN (SELECT emp.dept_id AS did,AVG(s.basic_salary) AS avg_salaryFROM t_employee AS emp,t_salary AS sWHERE emp.eid = s.eidGROUP BY emp.dept_id) AS tempON t_salary.eid = t_employee.eid AND t_employee.dept_id = temp.didWHERE t_salary.basic_salary > temp.avg_salary; |
3、exists型子查询
#exists型#查询部门信息,该部门必须有员工SELECT * FROM t_departmentWHERE 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%’;