我需要一些帮助来优化使用F#SqlDataConnection类型提供程序的查询。
有一个表Items
与其他4个表的关系:
Type - n : 1
SubItem1 - m : n
SubItem2 - m : n
SubItem3 - 1 : n
这是类型提供程序查询代码:
query {
for x in db.Items do
join t in db.ItemType on (x.Typy = t.Name)
select (x, t, x.ItemSubItem1, x.ItemSubItem2, x.SubItem3)
}
|> Seq.map toItem
它生成以下SQL语句:
SELECT [t0].[Id], [t0.Name], [t1].[Name], [t2].[ItemId], [t2].[SubItem1Id], (
SELECT COUNT(*)
FROM [dbo].[ItemSubItem1] AS [t3]
WHERE [t3].[ItemId] = [t0].[Id]
) AS [value]
FROM [dbo].[Item] AS [t0]
INNER JOIN [dbo].[ItemType] AS [t1] ON [t0].[Typ] = [t1].[Name]
LEFT OUTER JOIN [dbo].[ItemSubItem1] AS [t2] ON [t2].[ItemId] = [t0].[Id]
ORDER BY [t0].[Id], [t1].[Name], [t2].[SubItem1Id]
问题是只有Type
和SubItems1
加入。因此,当为toItem
中的每个条目调用Items
时,将生成2个额外的SQL查询以获取SubItem2
和SubItem3
。这是非常低效的。
感谢您的帮助!