更新:我有一个 sql 查询工作,但仍然无法将其转换为 linq2sql。请看下面的代码..
我有一个 linq 查询,它正在提取大量数据,但有时由于它在 sql 服务器上的负载而超时。我将致力于获取更有效的数据(添加索引等),但我也听说使用 group by 会比使用子查询更有效。group by 会更有效吗?如果是这样,我的查询在下面的 group by 中会是什么样子?我还不熟悉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();