美文网首页数据库
SQL之left join、right join、full jo

SQL之left join、right join、full jo

作者: laman_chen | 来源:发表于2017-08-18 11:44 被阅读31次

    前提:一个学生表Student,一个描述表Desc

    表数据:

    表数据

    left join:

    sql:

    SELECT * FROM Student

                      LEFT JOIN [Desc]

                      ON Student.ID=[Desc].ID


    linq:

    读取全部:

    from student in db.Student join desc in db.Desc on student.ID equals desc.StudentID into jointemp from temp in jointemp.DefaultIfEmpty() select new { student, temp };

    读取指定字段:

    from student in db.Student join desc in db.Desc on student.ID equals desc.StudentID into jointemp from temp in jointemp.DefaultIfEmpty()select new{ID =student.ID,Name =student.Name,Mark =temp.Mark};


    lambda:

    读取全部:

    db.Student.GroupJoin(db.Desc, u => u.ID, d => d.StudentID, (u, d) => new { u, d }).Select(o => o);

    读取指定字段:

    db.Student.GroupJoin(db.Desc, u => u.ID, d => d.StudentID, (u, d) => d.DefaultIfEmpty().Select(p => new {ID=u.ID,Name=u.Name,Mark=p.Mark })).SelectMany(o => o);


    right join:

    SELECT * FROM Student

    RIGHTJOIN [Desc]

    ON Student.ID=[Desc].ID

    PS:A left join B=B right join A


    对应linq以及lambda即调换两个表位置

    inner join:

    SELECT * FROM Student

    INNER JOIN [Desc]

    ON Student.ID=[Desc].ID


    linq:

    读取全部:

    from student in db.Student join desc in db.Desc on student.ID equals desc.StudentID select new { student, desc };

    读取指定字段:

    from student in db.Student join desc in db.Desc on student.ID equals desc.StudentID select new { ID = student.ID, Name = student.Name, Mark = desc.Mark };


    lambda:

    读取全部:

    db.Student.Join(db.Desc, u => u.ID, d => d.StudentID, (u, d) => new { u, d }).Select(o => o);

    读取指定字段:

    db.Student.Join(db.Desc, u => u.ID, d => d.StudentID, (u, d) =>new { ID = u.ID, Name = u.Name, Mark = d.Mark }).Select(o => o);

    full join:

    SELECT * FROM Student

    FULL JOIN [Desc]

    ON Student.ID=[Desc].ID

    corss join:

    SELECT * FROM Student

    CORSS JOIN [Desc]


    linq:

    读取全部

    from student in db.Student from desc in db.Desc select new { student, desc };

    读取指定字段

    from student in db.Student from desc in db.Desc select new { ID = student.ID, Name = student.Name, Mark = desc.Mark };

    lambda:

    读取全部

    读取指定字段

    相关文章

      网友评论

        本文标题:SQL之left join、right join、full jo

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