zoukankan      html  css  js  c++  java
  • MySQL left join 用法与实例

    mysql left join 会取得左表的全部数据,即使右表并无完全匹配的结果
    d表:

    [yoon]> select * from d;
    +----+----------+------+
    | id | number | name |
    +----+----------+------+
    | 1 | 12345 | aa |
    | 3 | 123456 | aa |
    | 5 | 1234567 | aa |
    | 7 | 12345678 | aa |
    +----+----------+------+

    hank表:

    [yoon]> select * from hank;
    +----+------+------+-----+
    | id | name | cc2 | cc3 |
    +----+------+------+-----+
    | 1 | YOON | NULL | 0 |
    | 3 | CEV | NULL | 0 |
    | 4 | AAA | NULL | 0 |
    | 5 | CCC | NULL | 0 |
    +----+------+------+-----+

    left join

    [yoon]> select d.id,d.number,hank.cc3 from d left join hank on d.id = hank.id;
    +----+----------+------+
    | id | number | cc3 |
    +----+----------+------+
    | 1 | 12345 | 0 |
    | 3 | 123456 | 0 |
    | 5 | 1234567 | 0 |
    | 7 | 12345678 | NULL |
    +----+----------+------+
    
    Using 相当于 on,如下:
    [yoon]> select d.id,d.number,hank.cc3 from d left join hank using(id);
    +----+----------+------+
    | id | number | cc3 |
    +----+----------+------+
    | 1 | 12345 | 0 |
    | 3 | 123456 | 0 |
    | 5 | 1234567 | 0 |
    | 7 | 12345678 | NULL |
    +----+----------+------+

    IS NULL:
    在上面语句中,右表中没有对应匹配的记录,其所有列都被置为 NULL ,因此要查询这部分数据,可以通过 where is null 来查询

    [yoon]> select d.id,d.number,hank.cc3 from d left join hank using(id) where hank.id is null;
    +----+----------+------+
    | id | number | cc3 |
    +----+----------+------+
    | 7 | 12345678 | NULL |
    +----+----------+------+
    或
    [yoon]> select d.id,d.number,hank.cc3 from d left join hank on d.id = hank.id where hank.id is null;
    +----+----------+------+
    | id | number | cc3 |
    +----+----------+------+
    | 7 | 12345678 | NULL |
    +----+----------+------+

    说明: hank.id is null 查询的是不匹配的值, hank.id is not null 查询的就是匹配到的值,如下:

    [yoon]> select d.id,d.number,hank.cc3 from d left join hank on d.id = hank.id where hank.id is not null;
    +----+---------+------+
    | id | number | cc3 |
    +----+---------+------+
    | 1 | 12345 | 0 |
    | 3 | 123456 | 0 |
    | 5 | 1234567 | 0 |
    +----+---------+------+
  • 相关阅读:
    Java中一对多映射关系
    Java中多对多映射关系
    java中的匿名内部类总结
    (自己转)比较ArrayList、LinkedList、Vector
    Statement 接口的应用(存在sql语句的注入风险)
    创建Jutil (单元测试)
    自己(转)抽象类和接口联系与区别
    SQL查询语句
    数据库基础查询语句中的几个细节
    数据库查询语句
  • 原文地址:https://www.cnblogs.com/hankyoon/p/13182573.html
Copyright © 2011-2022 走看看