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
    

    解析:

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

    下一章

    与外表之间

  • 相关阅读:
    Nhibernate代码生成器v2.1中文版
    在asp.net中生成16位随机密码
    IIS 启动不了(发生意外错误0x8ffe2740)
    NET代码生成器
    Linux系统
    VS2005快捷键大全
    ASP+ACCESS数据库中文乱码问题解决
    如何配置ASP.NETOracle 9i 远程登陆数据库
    ASP.NET获取汉字拼音的首字母
    checkbox 实时操作,勾选后变色[带演示]
  • 原文地址:https://www.cnblogs.com/aoximin/p/12545440.html
Copyright © 2011-2022 走看看