zoukankan      html  css  js  c++  java
  • mysql中exists和in的用法

    引用一篇分析比较好的文章:

    https://blog.csdn.net/zhenwei1994/article/details/82145711

    先看一道sql编程题

    使用含有关键字exists查找未分配具体部门的员工的所有信息。
    CREATE TABLE `employees` (
    `emp_no` int(11) NOT NULL,
    `birth_date` date NOT NULL,
    `first_name` varchar(14) NOT NULL,
    `last_name` varchar(16) NOT NULL,
    `gender` char(1) NOT NULL,
    `hire_date` date NOT NULL,
    PRIMARY KEY (`emp_no`));
    CREATE TABLE `dept_emp` (
    `emp_no` int(11) NOT NULL,
    `dept_no` char(4) NOT NULL,
    `from_date` date NOT NULL,
    `to_date` date NOT NULL,
    PRIMARY KEY (`emp_no`,`dept_no`));
    输出格式:

    emp_nobirth_datefirst_namelast_namegenderhire_date
    10011 1953-11-07 Mary Sluis F 1990-01-22

     解法有两种【in和exists】。题中提到只能用exists语句。所以以下解法合适:

    --1、exists
    select
    * from employees as a where not exists ( select 1 from dept_emp b where a.emp_no=b.emp_no )
    --2、in
    select
    * from employees where emp_no not in ( select a.emp_no from employees as a inner join dept_emp as b on a.emp_no=b.emp_no )

    考虑到查询的时间复杂度,exists和in使用场景分析如下:

    外查询数据量大,子查询数据量小,则使用in

    外查询数据量小,子查询数据量大,则使用exists

    因为使用in可以使用到两次索引,exists,外查询匹配是全表扫描

  • 相关阅读:
    Yii2 分页
    Yii2 或者当前登录用户帐号
    css3媒体查询判断移动设备横竖屏
    Javascript操作Tr隐藏显示变形~
    php注释标准
    匹配一段html中所有的src
    数据库遇到错误(随时补充)
    NetCore-缓存文件上传和文件流上传
    SVN跨服务器版本迁移
    发票同步微信卡包
  • 原文地址:https://www.cnblogs.com/yibao/p/13969217.html
Copyright © 2011-2022 走看看