• mysql-联合查询


    一.联合查询的概念

    .对于unio查询,就是把多次查询的结果合并起来,形成一个新的查询果集。

    1. SELECT 字段列表 FROM 表A...
    2. UNION[ALL]
    3. SELECT 字段列表 FROM 表B...,

    二.将薪资低于5000的员工,和年龄大于50岁的员工全部查询出来

    select * from emp  where salary<5000
    select * from emp  where age>50
    union all

    将上面的结果集合并起来,

    对查询的进行去重

    union 

    三.注意点

    1.对于联合查询多张表的列数必须保持一致,字段类型也必须保持一致。

    2.union all 会将全部的数据直接合并在一起,union会对合并之后的数据去重

    四.子查询

    1.概念

    SQL语句中嵌套SELECT语句,称为嵌套语句,又称子查询

    SELECT * FROM t1 WHERE column1=SELECT column1 FR0M t2);

    子查询外部的语句可以是INSERT/UPDATE/DELETE/SELECT的任何一个。

    五.标量子查询

    子查询返回的结果是单个值(数字,字符串,日期等),最简单的形式,这种子查询成为标量子查询

    常用的操作符:= <>  > >= < <=

    六.案例

    1.查询销售部的所有员工信息

    a.查询 销售部部门的id

    select id from dept where name='销售部';
    

    b.根据销售部 部门id

    select * from emp where dept_id=4

    select * from emp where dept_id=(select id from dept where name='销售部')

    2.查询在"方东白“入职之后的员工信息

    a.查询方东白的入职日期

    select  entrydate from emp where name="方东白"
    

    b.指定入职日期之后入职的员工

    select * from emp where entrydate>select  entrydate from emp where name="方东白");

    六.列子查询

    子查询返回的结果是一列(可以是多行),这种子查询称为列子查询

    常用的操作符:IN ,NOT IN ,ANY ,SOME,ALL

    七.案例

    1.查询销售部和市场部的所有员工信息

    a.查询销售部和市场部的部门ID

    select id from dept where name="销售部" or name="市场部";

    b.根据部门ID,查询员工信息

    select  * from  emp  where  dept_id in(24);

    合并:

    select  * from  emp  where  dept_id in(select id from dept where name="销售部" or name="市场部");

    2.查询比财务部 所有人工资都高的员工信息

    selec id from  dept where name="财务部"

     

    select salary from emp where dept_id=(selec id from  dept where name="财务部");

    b.比财务部 所有人工资都高的员工信息

    select * from emp where salary> all(select salary from emp where dept_id=(selec id from  dept where name="财务部"))

    子查询返回过来的结果都要去满足

    3.比研发部其中任意一人工资高的员工信息

    a.查询研发部所有人的工作

    select salary from emp where dept_id=(selec id from  dept where name="研发部");

    b.比研发部任意人高的员工工资

    selec * from emp where salary >any(select salary from emp where dept_id=(selec id from  dept where name="财务部"))

    子查询返回的就是单行多列的数据。

  • 相关阅读:
    责任链模式 行为型设计模式之十
    如何计算股票程序化交易系统的收益率?
    opencloudos容器镜像优化
    一种便捷的爬虫方法
    linux设备模型:固件设备及efi固件(平台)设备节点创建过程分析
    编译报错:undefined reference to `TIFFReadDirectory@LIBTIFF_4.0‘解决方法
    react编程式路由的基本知识
    易基因:鸡的chTERT靶基因DNA甲基化检测揭示ALV-J肿瘤发生机制|客户文章
    Bulk RNA-seq上下游分析
    PostgreSQL 认证方式
  • 原文地址:https://blog.csdn.net/qq_59076775/article/details/140404047