概念SQL语句中嵌套SELECT语句 称为嵌套查询 又称子查询
SELECT * FROM t1 WHERE colunm1 = (SELECT column1 FROM t2);
子查询外部的语句可以是INSERT/UPDATE/DELETE/SELECT
子查询语句位置可以WHERE FROM SELECT 之后
子查询例句
-变量子查询返回一个值 作为需要的字段条件 合并语句以后 就是标量子查询
(SELECT id(需要字段) FROM dept(表名) WHERE name(字段) = '销售部')
SELECT * FROM emp(表名) WHERE dept.id(条件字段) = 4
SELECT * FROM emp(表名) WHERE dept.id(条件字段) =(SELECT id(需要字段) FROM dept(表名) WHERE name(字段) = '销售部')
列子查询 -- 返回结果为一列
常用操作符 IN , NOT IN , ANY ,SOME, ALL
IN 在指定的集合范围之内 多选一
NOT IN 不在指定的集合范围之内
ANY 子查询返回列表中,有任意一个满足即可
SOME 与ANY等同,使用过SOME的地方都可以使用ANY
ALL 子查询返回列表的所有值都必须满足
例句
SELECT id FROM dept WHERE name='销售部' or name = '人力资源'
SELECT * FROM emp WHERE dept_id in (2 ,4)
合并后
SELECT * FROM emp WHERE dept_id in (SELECT id FROM dept WHERE name='销售部' or name = '人力资源')
行子查询 -- 返回结果为一行
常用操作符 IN , NOT IN , = ,<>
SELECT salary , mangerid FROM emp WHERE name = '张无忌'
SELECT * FROM emp WHERE (salary , managerid ) =(12500,1)
合并后
SELECT * FROM emp WHERE (salary , managerid ) =(SELECT salary , mangerid FROM emp WHERE name = '张无忌')
表子查询 -- 返回结果多行多列
常用操作符 IN
例句
SELECT job , salary FROM emp WHERE name ='鸡哥' or name = '巴哥'
SELECT * FROM emp WHERE (job , salary ) in (select job ,salary FROM emp WHERE name ='鸡哥' or name = '巴哥')