zoukankan      html  css  js  c++  java
  • sql 语句系列(null 值处理)[八百章之第二章]

    查找只存在一个表中的数据

    有两张表:
    EMP:
    select * from emp

    DEPT:

    他们有共同的属性:deptno

    现在要查询EMP 中的deptno不等于DEPTNO的deptno项。

    解析:

    select distinct DEPTNO from EMP where DEPTNO not in (
    select DEPTNO from DEPT
    )
    

    注意:

    因为需要查询的是DEPTNO,所以需要排除掉重复项。

    其次上面的写法,如果DEPTNO在DEPT有null项上面的是错误的。

    我在dept 中加入了 null 值:

    得到的结果为空。

    这里面关键点在于null的判断是 is 和 not is判断的。

    看下not in 的展开式:
    not in (DEPTNO=10||DEPTNO=20||DEPTNO=30||DEPTNO=40||DEPTNO=null)

    本来有结果有一个50是不属于他们的。

    那么把50输入进去会怎么样?

    not in(false||false||false||false||false||null)

    结果是not in (null)

    我尝试使用:

    select distinct DEPTNO from EMP where DEPTNO not in(null)
    

    结果也是空,说明转换逻辑是正确的。
    那么问题可以回到:

    select distinct DEPTNO from EMP where DEPTNO!=null
    

    因为null值不能通过!=判断,这样是不会返回结果的。

    下面是有null值的时候的写法:

    select distinct DEPTNO from EMP e  where not exists(
    select null from DEPT where e.DEPTNO=DEPT.DEPTNO
    )
    

    下面的not exists只需判断有和无,那么select null 换成其他也一样。

    从一个表检索与另一个表不相关的行

    这一个例子和上一个非常相似。

    查找出那些部门没有员工:

    select d.* from DEPT d left outer join EMP  e on e.DEPTNO=d.DEPTNO where e.DEPTNO is null
    

    解析:

    和上面不同的是上面是针对列,而这个是针对行。

    下一章

    与外表之间

  • 相关阅读:
    jmeter循环发送http请求
    判断字符串是否为日期格式
    正则表达式的部分替换 $1~$99
    js验证上传文件大小
    mongodb主从备份 和 手动主从切换
    openproject安装与使用
    软件项目开发常见错误
    使用selenium的WebDriver和ChromeDriver实现UI自动化
    shell ssh远程执行命令
    Flask入门
  • 原文地址:https://www.cnblogs.com/aoximin/p/12545440.html
Copyright © 2011-2022 走看看