【发布时间】:2015-04-14 10:06:48
【问题描述】:
我有以下查询可以正常工作
var myList = (from p in db.full
group p by p.object into g
orderby g.Count() descending
select new StringIntType
{
str = g.Key,
nbr = g.Count()
}).Take(50).ToList();
问题是它有点慢,因为我使用的是 count(),它被转换为 count(*)。
我需要知道是否有办法使用 count(object),
这是我在 sql server profiler 中得到的结果
exec sp_executesql N'SELECT TOP (50)
[Project1].[C2] AS [C1],
[Project1].[object] AS [object],
[Project1].[C1] AS [C2]
FROM ( SELECT
[GroupBy1].[A1] AS [C1],
[GroupBy1].[K1] AS [object],
1 AS [C2]
FROM ( SELECT
[Extent1].[object], AS [K1],
COUNT(1) AS [A1]
FROM (SELECT
[full].[mc_host_class] AS [mc_host_class],
[full].[event_handle] AS [event_handle],
[full].[mc_host_address] AS [mc_host_address],
[full].[mc_object_class] AS [mc_object_class],
[full].[mc_object] AS [mc_object],
[full].[mc_incident_time] AS [mc_incident_time],
[full].[date_reception] AS [date_reception],
[full].[status] AS [status],
[full].[mc_owner] AS [mc_owner],
[full].[msg] AS [msg],
[full].[duration] AS [duration],
[full].[repeat_count] AS [repeat_count],
[full].[mc_date_modification] AS [mc_date_modification],
[full].[event_class] AS [event_class],
[full].[bycn_ticket_remedy] AS [bycn_ticket_remedy],
[full].[mc_host] AS [mc_host],
[full].[acknowledge_by] AS [acknowledge_by],
[full].[acknowledge_by_time] AS [acknowledge_by_time],
[full].[assigned_by] AS [assigned_by],
[full].[assigned_to] AS [assigned_to],
[full].[assigned_by_time] AS [assigned_by_time],
[full].[closed_b y] AS [closed_by],
[full].[closed_by_time] AS [closed_by_time],
[full].[blacked_out] AS [blacked_out],
[full].[bycn_liaison_type] AS [bycn_liaison_type],
[full].[bycn_liaison_debit] AS [bycn_liaison_debit],
[full].[cause] AS [cause],
[full].[mc_location] AS [mc_location],
[full].[mc_parameter] AS [mc_parameter]
FROM [dbo].[full] AS [full]) AS [Extent1]
GROUP BY [Extent1].[object],
) AS [GroupBy1]
) AS [Project1]
ORDER BY [Project1].[C1] DESC',N'@p__linq__0 datetime2(7),@p__linq__1 datetime2(7)',@p__linq__0='2015-03-14 00:00:00',@p__linq__1='2015-04-15 00:00:00'
【问题讨论】:
-
在您的情况下,我认为 SqlProfiler 可以提供帮助。生成的查询似乎很简单,所以我不确定是否有机会进行优化,例如在 sql 中添加索引或其他性能技巧。
-
嗯,
nbr = g.Select(a => 1).Count()? -
@Jenea 在 sql profiler 中计算了表的所有列,这需要太多时间。
-
翻译后的查询中最里面的 SELECT 似乎没有必要。有没有办法让 linq 不生成它?
-
在我的代码中还是在 sql server profiler 中生成的代码中?
标签: c# asp.net sql-server linq