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 |
    +----+---------+------+
  • 相关阅读:
    5213 Exp3 免杀原理与实践
    20155213实验二 后门原理与实践
    20165110石钰网络对抗免考报告_WIFI破解+搭建钓鱼WIFI
    Exp9 Web安全基础 20165110
    Exp8:Web基础 20165110
    Exp7 网络欺诈防范 20165110
    Exp6 信息搜集与漏洞扫描 20165110
    Exp5 MSF基础应用 20165110
    Exp4 恶意代码分析 20165110
    Exp3 免杀原理与实践 20165110
  • 原文地址:https://www.cnblogs.com/hankyoon/p/13182573.html
Copyright © 2011-2022 走看看