zoukankan      html  css  js  c++  java
  • 数据库inner join语句复习

    今天遇到这样一个语句:

      select * from interface a inner join hosts b on a.hostid=b.hostid inner join items c on c.hostid=a.hostid where a.hostid=10084 and c.key_ like "%CPU%"\G;

    都忘了怎么回事了,下面学习一下,转至:https://www.cnblogs.com/Jessy/p/3525419.html

    原文有些错误,给纠正过来。

    sql(join on 和where的执行顺序)

    left join :左连接,返回左表中所有的记录以及右表中连接字段相等的记录。

    right join :右连接,返回右表中所有的记录以及左表中连接字段相等的记录。

    inner join: 内连接,又叫等值连接,只返回两个表中连接字段相等的行。

    full join:外连接,返回两个表中的行:left join + right join。

    cross join:结果是笛卡尔积,就是第一个表的行数乘以第二个表的行数。

    关键字: on

    数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。

    在使用left jion时,on和where条件的区别如下:

    1、 on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。

    2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。

    假设有两张表:

    表1:tab1

    id size
    1 10
    2 20
    3 30

    表2:tab2

    size name
    10 AAA
    20 BBB
    20 CCC

    两条SQL:
    1、select * form tab1 left join tab2 on (tab1.size = tab2.size) where tab2.name=’AAA’
    2、select * form tab1 left join tab2 on (tab1.size = tab2.size and tab2.name=’AAA’)

    第一条SQL的过程:
    1、中间表
    on条件:
    tab1.size = tab2.size
    tab1.id tab1.size tab2.size tab2.name
    1 10 10 AAA
    2 20 20 BBB
    2 20 20 CCC
    3 30 (null) (null)
       
    2、再对中间表过滤
    where 条件:
    tab2.name=’AAA’
    tab1.id tab1.size tab2.size tab2.name
    1 10 10 AAA
       
    第二条SQL的过程:
    1、中间表
    on条件:
    tab1.size = tab2.size and tab2.name=’AAA’
    (条件不为真也会返回左表中的记录)
    tab1.id tab1.size tab2.size tab2.name
    1 10 10 AAA
    2 20 (null) (null)
    3 30 (null) (null)

    其实以上结果的关键原因就是left join,right join,full join的特殊性,不管on上的条件是否为真都会返回left或right表中的记录,full则具有left和right的特性的并集。 而inner jion没这个特殊性,则条件放在on中和where中,返回的结果集是相同的。

    下面解释一下最开始的语句:

    select * from interface a inner join hosts b on a.hostid=b.hostid inner join items c on c.hostid=a.hostid where a.hostid=10084 and c.key_ like "%CPU%"\G;

    a--interface  b---hosts c----items表

    select * from interface  inner join hosts  on interface.hostid=hosts.hostid inner join items  on items.hostid=interface.hostid where interface.hostid=10084 and items.key_ like "%CPU%"\G;

    就是表的一个合并的意思。

  • 相关阅读:
    Docker之路-docker架构
    Docker之路-认识docker
    Docker之路-版本选择及安装
    Golang理解-集合
    大话算法-动态规划算法
    运维职责
    Golang理解-匿名结构体
    DotNetty项目基本了解和介绍
    变量声明在循环体内还是循环体外的争论
    SqlServer与MySql语法比较
  • 原文地址:https://www.cnblogs.com/zw2002/p/8085433.html
Copyright © 2011-2022 走看看