MySQL之子查询

子查询

测试数据
create table emp (id int,name char(10),sex char,age int,dept_id int,job char(10),salary double);

insert into emp values
(1,"刘备","男",26,1,"总监",5800),
(2,"张飞","男",24,1,"员工",3000),
(3,"关羽","男",30,1,"员工",4000),
(4,"孙权","男",25,2,"总监",6000),
(5,"周瑜","男",22,2,"员工",5000),
(6,"小乔","女",31,2,"员工",4000),
(7,"曹操","男",19,3,"总监",10000),
(8,"司马懿","男",24,3,"员工",6000);

create table dept(id int primary key,name char(10));
insert into dept values(1,"市场"),(2,"行政"),(3,"财务");
1. 什么是子查询

​ 当一个查询是另外一个查询的条件时,这个查询称之为子查询(内层查询)mysql

​ 何时用?sql

​ 当查询需求比较复杂,一次性查询没法获得结果,须要屡次查询时,测试

​ 例如:给出一个部门名称,须要得到该部门全部的员工信息spa

​ 分析:code

​ 1.须要先肯定部门的idtable

​ 2.而后才能经过id肯定员工class

​ 解决问题的方式是把一个复杂的问题拆分为若干个简单的问题select

2. 如何使用?

首先明确子查询就是一个普通的查询,当一个查询须要做为子查询使用时,用括号包裹便可im

3. 须要注意

​ in中的子查询只能包含一个列数据

​ 例如:查询财务部有哪些人

​ 正确的写法:select name from emp where dept_id in (select id from dept where name = "财务");

​ 错误的写法:select name from emp where dept_id in (select * from dept where name = "财务");

关键字:exists

exists后跟子查询,子查询有结果是为True,没有结果时为False。为True时外层执行,为False外层不执行

如何使用?

select *from emp where exists (select *from emp where salary > 1000);

前面 exists 后面 若是 后面 查询有结果时,前面 才会执行

相关文章
相关标签/搜索