[英]Query taking too long to execute in LINQ
I've written a query which should take all the rows from one table and do a subquery to a second table pulling only one value from the most recent record. 我编写了一个查询,该查询应该从一个表中获取所有行,并对第二个表进行子查询,从而仅从最新记录中提取一个值。 In SQL Server the query takes about 15 seconds to execute and the LINQ query takes close to 2 minutes.
在SQL Server中 ,查询大约需要15秒才能执行,而LINQ查询大约需要2分钟。 Can someone help me with translating the SQL to LINQ, I must have done something wrong along the way.
有人可以帮我将SQL转换为LINQ吗,在此过程中我一定做错了。
The SQL
: SQL
:
SELECT a.isrunning,
worktype = (
SELECT TOP 1
w.worktype
FROM dbo.workorder w WITH (NOLOCK)
WHERE w.assetnum = a.assetnum
ORDER BY w.statusdate DESC
),
a.status,
*
FROM dbo.asset a WITH (NOLOCK)
WHERE a.assetnum IN ('list', 'of', 'asset', 'numbers')
The LINQ
Query: LINQ
查询:
(
from a in db.assets
let wo = (
from w in db.workorders
where w.assetnum == a.assetnum
orderby w.statusdate descending
select w).FirstOrDefault()
where aliasStrings.Contains(a.assetnum)
select new AssetWithWorkType {
...
}
);
It is recommended to have indexes on foreign keys. 建议在外键上具有索引。 Also indexes that covers filtering and ordering clauses.
还包括过滤和排序子句的索引。 So I suggest you to create the following 3 indexes:
因此,我建议您创建以下3个索引:
CREATE NONCLUSTERED INDEX [IDX_workorder_statusdate] ON dbo.workorder(statusdate)
CREATE NONCLUSTERED INDEX [IDX_workorder_assetnum] ON dbo.workorder(assetnum)
If assetnum
column in asset
table is not the primary key then additionally: 如果
asset
表中的assetnum
列不是主键,则另外:
CREATE NONCLUSTERED INDEX [IDX_asset_assetnum] ON dbo.asset(assetnum)
You can create a temp table for the correlated subquery results, and then join it later. 您可以为相关的子查询结果创建一个临时表,然后再将其联接。 Syntax is not correct, as I dont have your table schemas or data, but the idea is the same.
语法不正确,因为我没有您的表架构或数据,但是想法是相同的。
CREATE TABLE #workTypes (worktype VARCHAR(X), assetnum VARCHAR(x))
INSERT INTO #workTypes
SELECT TOP 1 worktype, assetnum FROM dbo.workorder ORDER BY statusdate DESC
SELECT a.isrunning,
b.worktype,
a.status,
*
FROM dbo.asset a WITH (NOLOCK)
INNER JOIN #worktypes b
ON a.assetnum = b.assetnum
WHERE a.assetnum IN ('list', 'of', 'asset', 'numbers')
How about: 怎么样:
SELECT a.isrunning,
w.worktype,
cnt = count(*)
FROM dbo.asset a WITH (NOLOCK)
INNER JOIN dbo workorder w WITH (NOLOCK) on w.assetnum = a.assetnum
WHERE a.assetnum IN ('list', 'of', 'asset', 'numbers')
This would give you a count of worktypes for each asset and might allow the database server to optimize more efficiently. 这将为您提供每种资产的工作类型计数,并可能允许数据库服务器更有效地优化。 Also consider adding indices or using a temp table as other answers have suggested.
还可以考虑添加索引或使用临时表(如其他答案所示)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.