我使用Linq2Sql作为ORM并遇到以下问题:我有2个表,我们称之为客户端(id,name)和client_action(id,clientid,date)。 'client'表包含客户端,client_action包含用户操作的日志,我只需要第一个。
有一个linq2sql查询(带分页和排序),导致以下sql:
SELECT TOP (10) /* columns here */
FROM (
SELECT /* columns here */
FROM [dbo].[client] AS [t0]
CROSS APPLY ((
SELECT NULL AS [EMPTY]
) AS [t8]
OUTER APPLY (
SELECT [t9].[source]
FROM [action] AS [t9]
INNER JOIN (
SELECT MIN([t10].[actionID]) AS [value], [t10].[ClientID]
FROM [client_action] AS [t10]
GROUP BY [t10].[clientID]
) AS [t11] ON [t9].[ID] = [t11].[value]
WHERE [t0].[ID] = [t11].[ClientID]
) AS [t12])
) AS [t17]
WHERE /* filter for fields from the client table */
ORDER BY [t17].[date_created] DESC
该查询中存在逻辑错误,我更改了它。现在生成的sql如下所示:
SELECT TOP (10) /* columns here */
FROM (
SELECT /* columns here */
FROM (
SELECT /* columns here */
FROM [dbo].[client] AS [t0]
CROSS APPLY ((
SELECT NULL AS [EMPTY]
) AS [t3]
OUTER APPLY (
SELECT [t7].[value]
FROM (
SELECT [t5].[ClientID], (
SELECT TOP (1) [t6].[ID]
FROM [client_action] AS [t6]
WHERE [t5].[clientID] = [t6].[clientID]
ORDER BY [t6].[date_created]
) AS [value]
FROM (
SELECT [t4].[clientID]
FROM [client_action] AS [t4]
GROUP BY [t4].[clientID]
) AS [t5]
) AS [t7]
WHERE [t0].[ID] = [t7].[clientID]
) AS [t8])
LEFT OUTER JOIN [client_action] AS [t9] ON [t8].[value] = [t9].[ID]
) AS [t26]
) AS [t27]
WHERE /* filter for fields from client table */
ORDER BY [t27].[date_created] DESC
出现性能问题。我使用'SET STATISTICS IO ON'执行了两个查询并获得了有趣的结果:
因此它使第二个查询工作得慢得多。有没有办法'调整'查询,以便在过滤后尽可能应用'交叉申请'?
问题在于,有两个'交叉应用'并且有更多的连接,这一切都使得它的工作非常慢。我创建的索引可以提高查询的速度,但仍然足够慢,令人讨厌。
帮助帮助 帮助。