MySQL之子查询

MySQL之子查询

子查询(Subquery)指出现在其他SQL语句内的select子句
子查询嵌套查询内部,且必须出现在圆括号内
子查询可以包含多个关键字或条件,如distinct、group by、order by、limit等;
子查询的返回值可以使标量、一行、一列或子查询
子查询可以使用在from语句中(作为表),但是要使用别名

  1. 使用比较运算符的子查询

    语法结构: 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 = ‘超极本’);

  1. 使用[not] in的子查询
    语法结构: operand comparison_operator [not] in (subquery)
    = ANY 与 in 等效
    != ALL 和 <> ALL 与 not in 等效

  2. 使用[not] exists 的子查询
    如果子查询返回任何值,exists将返回true;否则,返回false。

  3. 使用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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值