zoukankan      html  css  js  c++  java
  • MySQL中Left Join和Right Join的理解

    虽然之前一直见过两个Join,对于其具体的含义也在参考书上读过,但是一直没有记住。现在换一种方式进行学习,改为实验方式理解。

    Left Join

    测试表:

    表结构很简单,test包括两个int字段,test2只包含一个int字段

    mysql> show create table testG 
    *************************** 1. row ***************************
           Table: test
    Create Table: CREATE TABLE `test` (
      `a` int(11) DEFAULT NULL,
      `b` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    1 row in set (0.01 sec)
    
    mysql> show create table test2G
    *************************** 1. row ***************************
           Table: test2
    Create Table: CREATE TABLE `test2` (
      `a` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8

    数据:

    mysql> select * from test;
    +------+------+
    | a    | b    |
    +------+------+
    |    1 |    1 |
    |    2 |    3 |
    |    4 |    5 |
    |    6 |    7 |
    +------+------+
    4 rows in set (0.00 sec)
    
    mysql> select * from test2;
    +------+
    | a    |
    +------+
    |    4 |
    |    6 |
    |    2 |
    |    8 |
    +------+

    使用Left Join输出:

    mysql> select * from test left join test2 on(test.a);
    +------+------+------+
    | a    | b    | a    |
    +------+------+------+
    |    1 |    1 |    4 |
    |    1 |    1 |    6 |
    |    1 |    1 |    2 |
    |    1 |    1 |    8 |
    |    2 |    3 |    4 |
    |    2 |    3 |    6 |
    |    2 |    3 |    2 |
    |    2 |    3 |    8 |
    |    4 |    5 |    4 |
    |    4 |    5 |    6 |
    |    4 |    5 |    2 |
    |    4 |    5 |    8 |
    |    6 |    7 |    4 |
    |    6 |    7 |    6 |
    |    6 |    7 |    2 |
    |    6 |    7 |    8 |
    +------+------+------+

    这就是笛卡尔积的表示

    加上test.a等于test2.a条件之后,对于test2中不存在记录使用NULL表示

    mysql> select * from test left join test2 on(test.a  = test2.a);
    +------+------+------+
    | a    | b    | a    |
    +------+------+------+
    |    1 |    1 | NULL |
    |    2 |    3 |    2 |
    |    4 |    5 |    4 |
    |    6 |    7 |    6 |
    +------+------+------+

    Right Join

    和Left Join相反

    Inner Join 

    对于上面同样的例子使用inner Join输出的记录中不会包含NULL字段:

    mysql> select * from test inner join test2 on(test.a  = test2.a);      
    +------+------+------+
    | a    | b    | a    |
    +------+------+------+
    |    4 |    5 |    4 |
    |    6 |    7 |    6 |
    |    2 |    3 |    2 |
    +------+------+------+
    3 rows in set (0.00 sec)
  • 相关阅读:
    fn project 试用之后的几个问题的解答
    fn project 扩展
    fn project 生产环境使用
    fn project 对象模型
    fn project AWS Lambda 格式 functions
    fn project 打包Function
    fn project Function files 说明
    fn project hot functions 说明
    fn project k8s 集成
    fn project 私有镜像发布
  • 原文地址:https://www.cnblogs.com/gsblog/p/3392993.html
Copyright © 2011-2022 走看看