0

我有两个表AB. AB一对多相关(A包含 的集合B)。

如何使实体框架生成下一个 SQL(我应该写什么 linq 查询):

SELECT A.UserId, COUNT(B.ID) FROM A
LEFT JOIN B ON A.ID = B.A_ID
WHERE B.Score <= 6
GROUP BY A.UserId

我尝试了下一个:

from a in db.A
join b in db.B 
on a.ID equals b.A_ID
where b.Score <= 6
group a by a.UserId into grouping
select new 
{
    UserId = (Guid) grouping.Key,                       
    RawValue = grouping.Sum(x => x.Bs.Count())
};

它返回了我需要的东西,但 EF 将其转换为可怕的查询(这就是为什么这个查询的性能非常糟糕)。

生成的 SQL:

SELECT 
1 AS [C1], 
[Project3].[UserId] AS [UserId], 
 CAST( [Project3].[C1] AS float) AS [C3]
FROM ( SELECT 
    [Project2].[UserId] AS [UserId], 
(SELECT 
    SUM([Filter2].[A1]) AS [A1]
    FROM ( SELECT 
        (SELECT 
            COUNT(1) AS [A1]
            FROM [dbo].[B] AS [Extent5]
            WHERE [Extent3].[ID] = [Extent5].[A_ID]) AS [A1]
        FROM  [dbo].[A] AS [Extent3]
        INNER JOIN [dbo].[B] AS [Extent4] ON [Extent3].[ID] = [Extent4].[A_ID]
        WHERE ([Extent4].[Score] <= 6) 
    )  AS [Filter2]) AS [C1]
FROM ( SELECT 
    [Distinct1].[UserId] AS [UserId]
    FROM ( SELECT DISTINCT 
        [Extent1].[UserId] AS [UserId]
        FROM  [dbo].[A] AS [Extent1]
        INNER JOIN [dbo].[B] AS [Extent2] ON [Extent1].[ID] = [Extent2].[A_ID]
        WHERE ([Extent2].[Score] <= 6) 
    )  AS [Distinct1]
)  AS [Project2]
)  AS [Project3]

预先感谢!

4

1 回答 1

0

当我改变你的 ef clouse

from a in db.A.DefaultIfEmpty()
        join b in db.B 
        on a.ID equals b.A_ID
        where b.Score <= 6
        group a by a.UserId into grouping
        select new 
        {
            UserId = (string) grouping.Key,                       
            RawValue = grouping.Count()
        };

我生成的 SQL 更改为

SELECT 
        1 AS [C1], 
        [GroupBy1].[K1] AS [UserId], 
        [GroupBy1].[A1] AS [C2]
        FROM ( SELECT 
            [Extent1].[UserId] AS [K1], 
            COUNT(1) AS [A1]
            FROM    ( SELECT 1 AS X ) AS [SingleRowTable1]
            LEFT OUTER JOIN [dbo].[A] AS [Extent1] ON 1 = 1
            INNER JOIN [dbo].[B] AS [Extent2] ON [Extent1].[ID] = [Extent2].[A_ID]
            WHERE [Extent2].[Score] <= 6
            GROUP BY [Extent1].[UserId]
        )  AS [GroupBy1]

我认为这是一个非常好的优化结果。

于 2013-01-02T14:13:14.690 回答