zoukankan      html  css  js  c++  java
  • 子查询

    所谓连表查询就是把两张表连接在一起之后,就变成一张大表,从from开始一直到on条件结束就看做一张表

    之后可以用where条件   group  by  分组   order  by   limit  都可以正常的使用

    子查询:

        select dep_id from employee group by dep_id having avg(age)>25;

            select name from department where id in (select dep_id from employee group by dep_id having avg(age)>25);

    查看技术部员工姓名:

          select id from department where name='技术';

              select name from employee where dep_id=(select id from department where name='技术');

    查看不足1人的部门名

        先把所有的部门id查出来   然后查询部门表,把不在所有部门id这个范围的dep_id 找出来

          select dep_id from employee group by dep_id;

              select name from department where id not in (select dep_id from employee group by dep_id);

         

    查询大于所有人平均年龄的员工名字与年龄

        求平均年龄                select   avg(age)   from    employee;  注意使用了聚合函数就相当于分组了,整张表就是一个组,

            select name,age from employee where age>(select avg(age) from employee);

    查询大于部门内平均年龄的员工名、年龄

        select t1.name,t1.age from employee as t1 inner join (select dep_id,avg(age) age2 from employee group by dep_id) as t2 on t1.dep_id=t2.dep_id where age>age2;          select t1.name,t1.age from employee as t1 inner join (select dep_id,avg(age) age from employee group by dep_id) as t2 on t1.dep_id=t2.dep_id having t1.age>t2.age;  注意:当两张表连接后首先必须用条件语句where才能用having。不能直接用having应该是having必须是在分组(group)之后才使用的。 

    带exists关键字的子查询。

    在使用时   例如:select    *    from     employee   where   exists   (   );如果后面成立,则执行。

    查询每个部门最新入职的那位员工

        select t1.name,t1.age,t1.hire_date,t1.post from employee as t1 inner join (select post,max(hire_date) max_date from employee group by post) as t2 on t1.post=t2.post where t1.hire_date=t2.max_date;

    如果一个问题既可以使用连表查询解决

    也可以使用子查询解决

    推荐使用连表查询,执行效率高

  • 相关阅读:
    go http client, http server
    如何使用Django 启动命令行及执行脚本
    golang cannot assign to
    非root用户执行程序---sudo的使用
    kafka 安装与配置
    golang kafka client
    Python处理Excel文档之openpyxl
    Windows下安装使用Pypcap
    xlutils模块
    Python xlrd、xlwt、xlutils修改Excel文件
  • 原文地址:https://www.cnblogs.com/ch2020/p/12913919.html
Copyright © 2011-2022 走看看