我正在尝试选择一个表并计算子表中所有已分配的行,但似乎存在性能问题?
当我对我们的Oracle DB运行这个Linq查询时,它永远不会停止:
From a In TABLE1
Select New With {
.ID = a.ID,
.COUNT = (From c In TABLE2 Where c.ID2 = a.ID).Count
}
当我在LINQPad中查看SQL时,它使用COALESCE和CASE进行如下翻译:
SELECT t0.ID, (
SELECT COUNT(*)
FROM TABLE2 t1
WHERE COALESCE(CASE WHEN ((t1.ID2 = t0.ID)) THEN 1 ELSE 0 END, 0) <> 0
) c0
FROM TABLE1 t0
当我对数据库运行我自己的查询时,它只需要大约5秒。
SELECT t0.ID, (
SELECT COUNT(*)
FROM TABLE2 t1
WHERE t1.ID2 = t0.ID
)
FROM TABLE1 t0
有没有办法在糟糕的翻译中消除COALESCE和CASE或在其他地方获得一些表现?
答案 0 :(得分:0)
你尝试使用GROUP JOIN吗?
From a In TABLE1
Join c In TABLE2 on c.ID2 Equals a.ID into g
Select New With {
.ID = a.ID,
.COUNT = g.Count
}
以下是生成的SQL:
SELECT [t0].[ID] AS [ID], (
SELECT COUNT(*)
FROM [TABLE2] AS [t1]
WHERE [t0].[ID] = ([t1].[ID2])
) AS [Count]
FROM [TABLE1] AS [t0]