SQL连接(内连接、外连接、交叉连接)

来源:互联网 发布:明治天皇 知乎 编辑:程序博客网 时间:2024/04/28 02:25

SQL连接(内连接、外连接、交叉连接)

假设现在有两个表:table1 table2

   table1                                table2
  id     name                          id     score  

  1       lee                            1        90  
  2       zhang                         2       100    
  4       wang                          3       70   

表的连接是针对列(属性),将两个表通过某种规则将两个表进行连接起来,一般是要么增加列或是减小列的个数,如

id    name    id    score   
  1    lee       1     90   

  2    zhang    2     100   

1)内联接:join     inner  join

select  *   from   1   join  2   on   两个表关联部分 where条件语句

如:

  select   *   from   table1   join  table2   on   table1.id=table2.id   

内联接是用比较运算符比较要联接列的值的联接只有两个表相匹配的行才进行连接 他等价

 select   a.*,b.*   from   table1   a,table2  b   where   a.id=b.id

结果:

 id    name    id    score   
  1    lee       1     90   

  2    zhang    2     100   

 

2)外连接(左连接、右连接、全连接)

左连接:left   join    left   outer   join   

select  *   from   1   left   join  2   on  两个表关联部分

select   *   from   table1   left   join  table2   on   table1.id=table2.id

左向外联接的结果集包括   LEFT   OUTER  子句中指定的左表的所有行,而不仅仅是联接列所匹配的行。如果左表的某行在右表中没有匹配行,则在相关联的结果集行中右表的所有选择列表列均为空值(null)   

结果

  1  lee     1      90   
  2  zhang  2     100   

  4  wang  NULL  NULL //左表的某行在右表中没有匹配行,右表填 null   

 

 右连接:right   join    right   outer   join   

select  *   from   1   right   join  2   on  两个表关联部分

select   *   from   table1   right  join   table2   on   table1.id=table2.id

 右向外联接是左向外联接的反向联接。将返回右表的所有行。如果右表的某行在左表中没有匹配行,则将为左表返回空值。    

结果

  id      name   id    score  
  1       lee    1     90  

  2       zhang  2    100   
 NULL  NULL   3    70  //右表的某行在左表中没有匹配行,左表填空值
 

 完整外部联接:full   join    full   outer   join    

select  *   from   1   full   join  2   on  两个表关联部分

select   *   from   table1   full   join  table2   on   table1.id=table2.id

完整外部联接返回左表和右表中的所有行。当某行在另一个表中没有匹配行时,则另一个表的选择列表列包含空值。如果表之间有匹配行,则整个结果集行包含基表的数据值。
结果

  id      name     id     score   
  1        lee      1        90   

  2       zhang    2        100   
  4       wang   NULL  NULL   
 
NULL  NULL   3        70   //某一个表中没有匹配行时,则另一个表填空值
    

3)交叉连接(完全,笛卡尔积) cross  join   (不带on条件where...)  

select  *   from   1   cross   join  2  

select   *  from   table1   cross   join   table2

没有 WHERE子句(或者是ON子句)的交叉联接将产生联接所涉及的表的笛卡尔积。第一个表的行数乘以第二个表的行数等于笛卡尔积结果集的大小。(table1table2交叉连接产生3*3=9条记录),他等价select   *   from   table1,table2  

结果
  id        name      id         score   

  1        lee          1         90  
  2        zhang       1         90  
  4        wang        1          90   
  1        lee          2         100  
  2        zhang        2        100   
  4        wang        2         100   
  1        lee           3          70   
  2        zhang        3          70   
  4        wang        3          70   

0 0
原创粉丝点击