加入3表 [英] Join 3 table

查看:71
本文介绍了加入3表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过LINQ加入3表,我这样做了:

var results = northwind.Products.Join(northwind.Categories,c => c.CategoryID,d => d.CategoryID ,(c,d)=> new {c.ProductID,c.ProductName,c.SupplierID,d.CategoryName})
.Where(q => q.ProductID> 12)
。 (northwind.Suppliers,f => f.SupplierID,g => g.SupplierID,(f,g)
=> new {f.CategoryName,f.ProductName,g.CompanyName,g.ContactName, g.Country});

但查询太长了,谁能告诉我写得更短?

谢谢。


解决方案

这是一种不同的编写方式,它更简洁,但最终两种方式在后端产生相同的SQL。


SELECT [t2]。[CategoryName],[t0]。[ProductName],[t1]。[CompanyName],[t1 ]。[ContactName],[t1]。[Country]


FROM [dbo]。[Products] AS [t0]


INNER JOIN [dbo]。[供应商] AS [t1] ON [t0]。[SupplierID] =([t1]。[SupplierID])


INNER JOIN [dbo]。[Categories] AS [t2] ON [t0]。[CategoryID] =([t2]。[CategoryID])


WHERE [t0]。[ProductID]> 12



var
qresult = from p in db .Products


其中 p.ProductID> ; 12


join s in db.Suppliers on p.SupplierID equals s.SupplierID


join c in db.Categories on p.CategoryID equals c.CategoryID


选择 new {c.CategoryName,p.ProductName,s.CompanyName,s.ContactName,s.Country};


I want to join 3 table by LINQ , i did this :

 var results = northwind.Products.Join(northwind.Categories, c => c.CategoryID, d => d.CategoryID, (c, d) => new { c.ProductID, c.ProductName, c.SupplierID, d.CategoryName })
                                            .Where(q => q.ProductID > 12)
                                            .Join(northwind.Suppliers, f => f.SupplierID, g => g.SupplierID, (f, g)
=> new { f.CategoryName, f.ProductName, g.CompanyName, g.ContactName, g.Country });

but the query is too long, who can tell me to write it shorter ?

thank.

         

解决方案

This is a different way to write it which is a little cleaner, but in the end both ways produce the same exact SQL on the back end.

SELECT [t2].[CategoryName], [t0].[ProductName], [t1].[CompanyName], [t1].[ContactName], [t1].[Country]

FROM [dbo].[Products] AS [t0]

INNER JOIN [dbo].[Suppliers] AS [t1] ON [t0].[SupplierID] = ([t1].[SupplierID])

INNER JOIN [dbo].[Categories] AS [t2] ON [t0].[CategoryID] = ([t2].[CategoryID])

WHERE [t0].[ProductID] > 12



var
qresult = from p in db.Products

where p.ProductID > 12

join s in db.Suppliers on p.SupplierID equals s.SupplierID

join c in db.Categories on p.CategoryID equals c.CategoryID

select new {c.CategoryName, p.ProductName, s.CompanyName, s.ContactName, s.Country };


这篇关于加入3表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆