美文网首页
mysql的inner join,left jion,right

mysql的inner join,left jion,right

作者: dancer4code | 来源:发表于2019-09-28 21:52 被阅读0次

    建立两个模拟表student表和course表

    student和course表.jpg

    1.cross join

    A表和B表求乘积(即笛卡尔积)

    select * from student ,course ;
    等于
    select * from student  CROSS JOIN  course ;
    

    查询的是笛卡尔乘积student(5)Xcourse(4)=20条

    select * from student  cross join  course on  student.id = course.student_id;
    相同
    select * from student , course where  student.id = course.student_id;
    

    查询结果是:

    cross join on 结果集.jpg

    所有限制条件where是通用的
    而on只能运用于配合各种join查询

    2. inner join

    在没有限制条件的情况下相同

    select * from student  inner join course ;
    等于
    select * from student ,course ;
    等于
    select * from student  CROSS JOIN  course ;
    

    都是取得20条记录

    限制条件下与cross基本相同。

    select * from student  cross join  course on  student.id = course.student_id;
    相同
    select * from student , course where  student.id = course.student_id;
    相同
    select * from student inner join course on  student.id = course.student_id;
    

    3. left join

    以左表为主,右表不符合条件的补null

    select * from student left join course on  student.id = course.student_id;
    

    结果


    left join.jpg

    4 left join

    以右表为主,左表不符合条件的补null

    select * from student right join course on  student.id = course.student_id;
    

    结果:


    right join.jpg

    左连接可以转成右连接

    select * from student left join course on  student.id = course.student_id;
    相同
    select * from  course right join student on  student.id = course.student_id;
    

    5 on和where

    on只能和各种连接联合使用select中
    where可以用在各种语句上select 、insert、update、delete .....

    注意

    select * from student left join course  on 1=1 where  student.id = course.student_id;
    相同
    select * from student , course  where  student.id = course.student_id;
    

    加上where条件后则不是以左表为主了!

    相关文章

      网友评论

          本文标题:mysql的inner join,left jion,right

          本文链接:https://www.haomeiwen.com/subject/lzsayctx.html