MySQL之子查询
子查询(Subquery)指出现在其他SQL语句内的select子句
子查询嵌套查询内部,且必须出现在圆括号内
子查询可以包含多个关键字或条件,如distinct、group by、order by、limit等;
子查询的返回值可以使标量、一行、一列或子查询
子查询可以使用在from语句中(作为表),但是要使用别名
-
使用比较运算符的子查询
语法结构: operand comparison_operator subquery
例子:
查询与SCOTT同一个部门的员工
select * from emp where deptno = (select deptno from emp where ename = ‘SCOTT’);
查询工资高于JONES的员工
select * from emp where sal > (select sal from emp where ename = ‘JONES’);
查询工资高于30号部门所有人的员工信息
select * from emp where sal > (select max(sal) from emp where deptno = 30);
查询工作和工资与MARTIN完全相同的员工信息
select * from emp where (job,sal) in(select job,sal from emp where ename = ‘MARTIN’);当返回值为多个的时候,可以使用ANY、SOME、ALL修饰
例子:
查询表中价格高于超极本的商品信息
select goods_id,goods_name,goods_price from tdb_goods where goods_price > ANY(select goods_price from tdb_goods where goods_cate = ‘超极本’);
-
使用[not] in的子查询
语法结构: operand comparison_operator [not] in (subquery)
= ANY 与 in 等效
!= ALL 和 <> ALL 与 not in 等效 -
使用[not] exists 的子查询
如果子查询返回任何值,exists将返回true;否则,返回false。 -
使用insert…select插入记录
insert (into) table_name [(column_name,...)] select ...
例子:
向tdb_goods_cates表插入数据,使用select从tdb_goods中查到goods_cate
insert tdb_goods_cates (cate_name) select goods_cate from tdb_goods group by goods_cate;