为什么实体框架linq查询的内部sql中没有groupby子句?

c9x0cxw0  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(322)

实体框架文件:https://www.entityframeworktutorial.net/querying-entity-graph-in-entity-framework.aspx
在关于groupby的部分中,我们可以阅读以下代码:

using (var ctx = new SchoolDBEntities())
{    
    var students = from s in ctx.Students 
                group s by s.StandardId into studentsByStandard
                select studentsByStandard;

    foreach (var groupItem in students)
    {
        Console.WriteLine(groupItem.Key);

        foreach (var stud in groupItem)
        {
            Console.WriteLine(stud.StudentId);
        }
    }
}

在内部执行以下sql:

SELECT 
[Project2].[C1] AS [C1], 
[Project2].[StandardId] AS [StandardId], 
[Project2].[C2] AS [C2], 
[Project2].[StudentID] AS [StudentID], 
[Project2].[StudentName] AS [StudentName], 
[Project2].[StandardId1] AS [StandardId1]
FROM ( SELECT 
    [Distinct1].[StandardId] AS [StandardId], 
    1 AS [C1], 
    [Extent2].[StudentID] AS [StudentID], 
    [Extent2].[StudentName] AS [StudentName], 
    [Extent2].[StandardId] AS [StandardId1], 
    CASE WHEN ([Extent2].[StudentID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2]
    FROM   (SELECT DISTINCT 
        [Extent1].[StandardId] AS [StandardId]
        FROM [dbo].[Student] AS [Extent1] ) AS [Distinct1]
    LEFT OUTER JOIN [dbo].[Student] AS [Extent2] ON ([Distinct1].[StandardId] = [Extent2].                                                [StandardId]) OR (([Distinct1].[StandardId] IS NULL) AND ([Extent2].[StandardId] IS NULL))
)  AS [Project2]
ORDER BY [Project2].[StandardId] ASC, [Project2].[C2] ASC
go

为什么sql中没有groupby子句?如果不需要groupby子句,我们就不能使用带orderby和不带join的simple select吗?有人能解释一下上述问题吗?

3b6akqbq

3b6akqbq1#

底线是:因为sql不能返回嵌套的结果集。
每个sql SELECT 语句返回值的平面列表。linq能够返回对象图,即具有嵌套对象的对象。这正是林克的想法 GroupBy 做。
在sql中,一个 GROUP BY 语句只返回分组列和聚合结果:

SELECT StandardId, COUNT(*)
FROM Students
GROUP BY StandardId;

剩下的学生专栏都不见了。
林肯 GroupBy 语句返回类似

StandardId
            StudentId StudentName
1
            21        "Student1"
            15        "Student2"
2
            48        "Student3"
            91        "Student4"
            17        "Student5"

因此,一个sql GROUP BY 语句永远不能是linq的源 GroupBy .
实体框架(6)知道这一点,它生成一个sql语句,从数据库中提取所有必需的数据,添加一些使分组更容易的部分,并在客户端创建分组。

相关问题