更新:我有一个SQL查询工作,但仍然无法将其转换为linq2sql。请参阅下面的代码..
我有一个linq查询,它会提取大量数据但有时由于它在sql服务器上的负载而超时。我将致力于获得更高效的数据(添加索引等),但我也听说使用group by比使用子查询更有效。一个群体是否会更有效率,如果是这样,我的查询下面的群组会是什么样子?我还不熟悉。请不要使用lambda
编辑:新查询仍然很慢并且可以超时:
var query = (from s in db.ZipCodeServiceAvailabilities
join a in db.pdx_apart_views on s.ZipCode equals a.Zip_Code.Substring(0, 5) into a_join
from a in a_join.DefaultIfEmpty()
join b in db.ZipCodeBoundaries on s.ZipCode equals b.ZipCode into b_join
from b in b_join.DefaultIfEmpty()
where
(s.IsServiced == 1 &&
b.Ordering % 10 == 0 &&
s.State == "AL")
group new { s, b, a } by new
{
s.ZipCode,
s.IsServiced,
b.Longitude,
b.Latitude,
b.Ordering
} into g
orderby
g.Key.ZipCode,
g.Key.Ordering
select new
{
g.Key.ZipCode,
apartCount = g.Count(p => p.a.Apartment_complex != null),
Longitude = g.Key.Longitude,
Latitude = g.Key.Latitude
}).ToArray();
编辑:在linq2sql(非常快)中使用我想要的sql进行查询:
select s.ZipCode, count(distinct ident) ApartCount, b.Longitude, b.Latitude from ZipCodeServiceAvailability s
left join pdx_apart_view
on s.ZipCode = left([Zip Code], 5)
left join ZipCodeBoundaries b
on s.ZipCode = b.ZipCode
Where IsServiced = 1 and and Ordering % 10 = 0 and State = 'AL'
Group By s.ZipCode, IsServiced, b.Longitude, b.Latitude, b.Ordering
Order by s.ZipCode, b.Ordering
原始查询非常慢:
var zips = (from s in db.ZipCodeServiceAvailabilities
join b in db.ZipCodeBoundaries on s.ZipCode equals b.ZipCode
where (s.IsServiced == service
&& b.Ordering % 10 == 0
&& s.State.Contains(state))
orderby b.ZipCode
select new
{
zipCode = b.ZipCode.Trim(),
latitude = b.Latitude,
longitude = b.Longitude,
apartCount = (from a in db.pdx_apart_views
where a.Zip_Code.Remove(5) == b.ZipCode
select a.Apartment_complex).Count()
}).ToArray();
答案 0 :(得分:2)
你的意思是你不熟悉一般的分组,或者只是在linq上下文中?
当我没有实体定义时,我发现编写纯SQL而不是linq更容易,下面是我认为你在SQL中寻找的东西 - 转换回linq应该是相当简单的。
select
b.ZipCode zipCode,
b.Latitude latitude,
b.Longitude longitude,
count(a.Apartment_complex) apartCount
from
ZipCodeServiceAvailabilities s
join ZipCodeBoundaries b
on s.ZipCode = b.ZipCode
left join pdx_apart_views a
on substring(a.Zip_Code, 1, 5) = b.ZipCode
group by
ZipCode,
Latitude,
Longitude
答案 1 :(得分:1)
在没有破坏索引的情况下,无法在linq2sql中复制左[(zip code),5] sql方法。答案是直接使用ado.net,所以我得到了所有的sql功能。