如何左连接两个父子表(即4个表)

时间:2016-03-14 00:29:20

标签: sql-server c#-4.0 entity-framework-6

我们有以下数据库结构:

Database diagram

我们如何查询属于特定客户端和组的所有数据? (使用Entity Framework 6编写的示例非常棒。)

我们可以这样做:

var parentChild1 = dbcontext.Parent1.Include(p => p.Child1).Select(p => p.ClientId = clientId).ToList();
var parentChild2 = dbcontext.Parent2.Include(p => p.Child2).Select(p => p.GroupId = groupId).ToList();
// And the manually join the values in parentChild2 with the objects in parentChild1.
// But there has to be a better way than this.

我在想这样的事情;但无法弄清楚如何将child1(s)与child2(s)连接起来:

void GetData(int clientId, int groupId)
{
    var query = (from p1 in dbcontext.Parent1
                 from c1 in dbcontext.Child1
                 where p1.ClientId == clientId && c1.Parent1Id == p1.Id
                 join p2 in dbcontext.Parent2.Where(p2 => p2.GroupId == groupId) 
                     on p1.Id equals p2.Parent1Id into p2groups
                 join c2 in dbcontext.Child2 on c1.Id equals c2.Child2Id into c2groups
                 from p2g in p2groups.DefaultIfEmpty()
                 from c2g in c2groups.DefaultIfEmpty()
                 select new Parent1
                 {
                     Parent2s = p2g,
                     //Child1s = c2g ??? How to wire up child1s with child2s?
                 };
}

1 个答案:

答案 0 :(得分:0)

以下sql语句应该从所有表中返回属于单个parent1Id和groupId的所有数据。

SELECT *
FROM Parent1 p1
LEFT JOIN Parent2 p2 ON(p1.Id = p2.Parent1Id AND p2.GroupId = @groupId)
LEFT JOIN Child1 c1 ON(p1.id = c1.Parent1Id)
LEFT JOIN Child2 c2 ON(c1.id = c2.Childe1Id AND p2.id = c2.Parent2Id)
WHERE p1.Id = @Id 

子连接是左连接,因为我假设并非所有父母都有子节点,但父连接是内连接,因为您需要groupid以及parent1 id。