我想知道为什么生成的SQL检查不可为空的列上的空值(列Value
是非空浮点数),
var query = _context.Events
.Select(e => new
{
eventId = e.EventId,
data = e.Data.Take(10).Select(x => new
{
name = x.Name,
value = Math.Round(x.Value,1),
})
});
生成以下SQL代码:
SELECT
[Project2].[EventId] AS [EventId],
[Project2].[DeviceId] AS [DeviceId],
[Project2].[TimeEnd] AS [TimeEnd],
[Project2].[C2] AS [C1],
[Project2].[EventId1] AS [EventId1],
[Project2].[Name] AS [Name],
[Project2].[C1] AS [C2]
FROM ( SELECT
[Limit1].[EventId] AS [EventId],
[Limit1].[TimeEnd] AS [TimeEnd],
[Limit1].[DeviceId] AS [DeviceId],
[Extent2].[Name] AS [Name],
[Extent2].[EventId] AS [EventId1],
CASE WHEN ([Extent2].[Value] IS NULL) THEN CAST(NULL AS float) ELSE ROUND([Extent2].[Value], 1) END AS [C1],
CASE WHEN ([Extent2].[Value] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2]
FROM (SELECT [Project1].[EventId] AS [EventId], [Project1].[TimeEnd] AS [TimeEnd], [Project1].[DeviceId] AS [DeviceId]
FROM ( SELECT
[Extent1].[EventId] AS [EventId],
[Extent1].[TimeEnd] AS [TimeEnd],
[Extent1].[DeviceId] AS [DeviceId]
FROM [dbo].[Events] AS [Extent1]
WHERE ([Extent1].[DeviceId] = 1)
) AS [Project1]
ORDER BY [Project1].[TimeEnd] DESC ) AS [Limit1]
LEFT OUTER JOIN [dbo].[Octaves] AS [Extent2] ON [Limit1].[EventId] = [Extent2].[EventId]
) AS [Project2]
ORDER BY [Project2].[TimeEnd] DESC, [Project2].[EventId] ASC, [Project2].[C2] ASC
如果我删除了两个CASE WHEN ([Extent2].[Value] IS NULL)
并离开ROUND([Limit2].[Value], 1) AS [C1]
并删除了SQL Server Management中的ORDER BY Project2].[C2] ASC
,则查询速度会加快。
答案 0 :(得分:2)
有一个LEFT OUTER JOIN,因此值(在查询中)绝对可以为NULL(即使基础表定义不可为空)。
请参阅http://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj18922.html(对于Oracle - 但相同的基本模式适用于所有主要SQL供应商)。
在这种情况下,它有点无意义,因为ROUND(NULL,1)无论如何都会返回NULL(好吧,它会在SQL Server上)。但是,由于无法控制它生成的SQL,因此您无法做很多事情。