Linq学习-多表连接

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linq学习-多表连接相关的知识,希望对你有一定的参考价值。

本将主要介绍 内连接与 外连接

1.join

Linq to sql

from a in Blog_Users
join b in Blog_UserInfo
on  a.UserId equals b.ID
select new
{
    昵称=a.NickName,
    真实名=b.RealName
}

sql

SELECT [t0].[NickName] AS [昵称], [t1].[RealName] AS [真实名]
FROM [Blog_User] AS [t0]
INNER JOIN [Blog_UserInfo] AS [t1] ON ([t0].[UserId]) = [t1].[ID]

Lambda

Blog_Users
   .Join (
      Blog_UserInfo, 
      a => (Int32?)(a.UserId), 
      b => b.ID, 
      (a, b) => 
         new  
         {
            昵称 = a.NickName, 
            真实名 = b.RealName
         }
   )

2.外连接

Linq to sql

from a in Blog_Users
join b in Blog_UserInfo
on  a.UserId equals b.ID
into ab
from c in ab.DefaultIfEmpty()
select new
{
    昵称=a.NickName,
    真实名=c.RealName
}

sql

SELECT [t0].[NickName] AS [昵称], [t1].[RealName] AS [真实名]
FROM [Blog_User] AS [t0]
LEFT OUTER JOIN [Blog_UserInfo] AS [t1] ON ([t0].[UserId]) = [t1].[ID]

Lambda

Blog_Users
   .GroupJoin (
      Blog_UserInfo, 
      a => (Int32?)(a.UserId), 
      b => b.ID, 
      (a, ab) => 
         new  
         {
            a = a, 
            ab = ab
         }
   )
   .SelectMany (
      temp0 => temp0.ab.DefaultIfEmpty (), 
      (temp0, c) => 
         new  
         {
            昵称 = temp0.a.NickName, 
            真实名 = c.RealName
         }
   )

以上是关于Linq学习-多表连接的主要内容,如果未能解决你的问题,请参考以下文章

linq多表join与group

c# Linq left join 多个条件连接查询

SQL学习多表关联-join

MySQL学习16:多表连接

数据库(学习整理)Oracle多表查询,三种join连接

数据库(学习整理)Oracle多表查询,三种join连接