美文网首页
Mysql之子查询

Mysql之子查询

作者: 数据分析之路 | 来源:发表于2018-07-15 10:57 被阅读0次

一、子查询使用场景

--select...

--<select 可用子查询>

--from

--where<可使用子查询>

--having<可使用子查询>

二、select中使用子查询

需求:查询各个部门中所有大于本部门平均工资的员工信息

select a.* from infor a,

(select deptno,avg(sal) as salAvg from infor group by deptno) b

where a.deptno=b.deptno and a.sal > b.salAvg;

三、where中使用子查询

1、in子查询

需求:查询各个部门中工资最高的员工信息

select * from infor where sal in

(select max(sal) from infor group by deptno);

2、where第二种子查询

需求:查询各个部门工资最高的两名员工信息

select * from infor e1 where 

(select count(1) from infor e2 where e2.deptno=e1.deptno and e2.sal>=e1.sal) < 3;

四、having中使用子查询

1、和一个比

需求:比用户tx订单数多的customer_id、city和订单数

select t1.customer_id,t1.city,count(t2.order_id) as amount from table1 t1,table2 t2

where t1.customer_id=t2.customer_id and t1.customer_id <>'tx'

group by customer_id

having (amount)>

(select count(order_id) from table2  where customer_id = 'tx' group by custer_id)

2、和多个比

需求:查询比customer_id为tx或者9you的订单数量最多的用户的id、城市和订单数量

select t1.custer_id,t1.city,count(t2.order_id) as amount from table1 t1,table2 t2

where t1.customer_id=t2.customer_id and t1.customer_id<>'tx' and t1.customer_id<>'9you'

group by customer_id having (amount) > any

(select count(order_id) from table2  where customer_id = 'tx'  or cusomer_id='9you' 

group by custer_id)

相关文章

  • MySQL之子查询

    本文主要介绍MySQL中的子查询,及如何使用它。 I、利用子查询进行过滤 假设我们有三个tables:1、orde...

  • Mysql之子查询

    一、子查询使用场景 --select... -- --from --where<可使用子查询> --having<...

  • MySQL多表之子查询

    子查询是指一个查询语句嵌套在另一个查询语句内部的查询。 它可以嵌套在一个SELECT || SELECT.......

  • MySQL(九)DQL之子查询

    一、含义 嵌套在其他语句内部的select语句称为子查询或内查询,外面的语句可以是insert、update、de...

  • MySQL | 数据查询语言之子查询

    子查询 分治思想. 复杂的查询分解为若干个简单的查询 ▲ 子查询的引入 #找出商店售价比 诺基亚E66 要贵的产品...

  • MySQL数据库之子查询与合并查询

    温馨提示:本文阅读需要5分钟,建议收藏后阅读! 各位宝宝们 我们今天一起来了解 MySQL数据库的子查询与合并查询...

  • 2018-03-20

    MYSQL查询语句 MYSQL复杂操作语句 MYSQL多表查询方法 函数部分

  • 高性能的索引策略

    MySQL查询基础-查询执行过程 MySQL聚簇索引 MySQL覆盖索引 MySQL索引扫描排序 MySQL冗余和...

  • MySQL学习——查询缓存

    MySQL查询缓存简介 MySQL查询缓存是MySQL将查询返回的完整结果保存在缓存中。当查询命中该缓存,MySQ...

  • MySQL学习-数据查询语言(DQL)五之子查询

    八丶子查询 1)含义:出现在其他语句中的select语句,称为子查询或内查询外部的查询语句,称为主查询或外查询 2...

网友评论

      本文标题:Mysql之子查询

      本文链接:https://www.haomeiwen.com/subject/fvxppftx.html