zoukankan      html  css  js  c++  java
  • mysql 内联接、左联接、右联接、完全联接、交叉联接 区别

    测试表SQL语句

    create table a (
        id int unsigned not null primary key auto_increment,
        name char(50) not null default ''
    )engine=myisam default charset=utf8;
    
    create table b (
        id int unsigned not null primary key auto_increment,
        name char(50) not null default '',
        a_id int not null
    )engine=myisam default charset=utf8;
    
    insert into a values
    (null,'张三'),
    (null,'李四'),
    (null,'王五');
    
    insert into b values
    (null,'tom',1),
    (null,'jack',2),
    (null,'wally',1),
    (null,'joan',4);

    表结果:

    表a.        表b

     

    内连接(join 或 inner join):使用比较运算符根据每个表共有的列的值匹配两个表中的行

    /*内联接*/
    select a.*,b.*
    from a
    inner join b
    on a.id = b.a_id;
    
    /*相当于*/
    select a.*,b.*
    from a,b 
    where a.id = b.a_id;

    外联接。外联接可以是左向外联接、右向外联接或完整外部联接。

    左外联接(left join 或 left outer join):如果左表的某行在右表中没有匹配行,则在相关联的结果集行中右表的所有选择列表列均为空值。 

    /*左外联接*/
    select a.*,b.*
    from a
    left join b
    on a.id = b.a_id;

    右外联接(right join 或 right outer join):左向外联接的反向联接。将返回右表的所有行。如果右表的某行在左表中没有匹配行,则将为左表返回空值。 

    /*右外联接*/
    select a.*,b.*
    from a
    right join b
    on a.id = b.a_id;

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

    /*全联接*/
    select a.*,b.*
    from a 
    full join b 
    on a.id = b.a_id;

    结果报错,什么原因?

     
    交叉连接(cross join):没有WHERE 子句的交叉联接将产生联接所涉及的表的笛卡尔积。第一个表的行数乘以第二个表的行数等于笛卡尔积结果集的大小。(table1和table2交叉连接产生3*3=9条记录)
     
    /*交叉联接(带where语句)*/
    select a.*,b.*
    from a 
    cross join b 
    on a.id = b.a_id;

    /*交叉联接(不带where语句)*/
    select a.*,b.*
    from a 
    cross join b;

    /*相当于*/
    select a.*,b.* from a,b;

     
  • 相关阅读:
    poj1860 Currency Exchange
    poj1062 昂贵的聘礼
    CF811C Vladik and Memorable Trip
    vs2012 jsoncpp 链接错误
    poj1923 Fourier's Lines
    excel中的表格转换成word中表格
    C:Program FilesMSBuildMicrosoft.Cppv4.0V110Microsoft.CppCommon.targets(249,5): error MSB6006: “CL.exe”已退出,代码为 -1073741515。
    poj1129 Channel Allocation
    POJ 2771 Guardian of Decency(求最大点独立集)
    POJ 1724 Roads
  • 原文地址:https://www.cnblogs.com/inuex/p/4320688.html
Copyright © 2011-2022 走看看