【发布时间】:2014-06-06 16:09:20
【问题描述】:
我正在尝试创建与此类似的查询:
select randomId
from myView
where ...
group by randomId
注意:EF 不支持 distinct 所以我想用 group by 解决它的不足(或者我认为)
randomId 是数字
实体框架 V.6.0.2
这给了我
当我尝试对 EF 做同样的事情时,我遇到了一些问题。
如果我执行类似于此的 LINQ:
context.myView
.Where(...)
.GroupBy(mt => mt.randomId)
.Select({ Id = group.Key, Count = group.Count() } )
我将得到相同的结果,但强制 count 并使查询 > 6 秒
SQL EF 生成的内容是这样的:
SELECT
1 AS [C1],
[GroupBy1].[K1] AS [randomId],
[GroupBy1].[A1] AS [C2]
FROM (
SELECT
[Extent1].[randomId] AS [K1],
COUNT(1) AS [A1]
FROM [dbo].[myView] AS [Extent1]
WHERE (...)
GROUP BY [Extent1].[randomId]
) AS [GroupBy1]
但是,如果查询将计数注释掉,它将返回到
如果我将 Select 更改为:
.Select({ Id = group.Key} )
我将在 SQL 查询中获取所有没有 group by 语句的行,并且没有任何 Distinct:
SELECT
[Extent1].[anotherField] AS [anotherField], -- 'this field got included automatically on this query and I dont know why, it doesnt affect outcome when removed in SQL server'
[Extent1].[randomId] AS [randomId]
FROM [dbo].[myView] AS [Extent1]
WHERE (...)
其他失败的尝试:
query.GroupBy(x => x.randomId).Select(group => group.FirstOrDefault());
生成的查询如下:
SELECT
[Limit1].ALL FIELDS,...
FROM (SELECT
[Extent1].[randomId] AS [randomId]
FROM [dbo].[myView] AS [Extent1]
WHERE (...) AS [Project1]
OUTER APPLY (SELECT TOP (1)
[Extent2].ALL FIELDS,...
FROM [dbo].[myView] AS [Extent2]
WHERE (...) AS [Limit1] -- same as the where above
此查询执行得相当糟糕,但仍设法返回 where 子句的所有 Id。
有没有人知道如何在没有像计数这样的聚合函数的情况下强制使用 group by?
在 SQL 中它可以工作,但我也有 distinct 关键字......
干杯, J
【问题讨论】:
-
刚刚验证 - 如果只选择分组键,则使用 MS SQL 的默认 EF 提供程序生成 DISTINCT 查询
-
@SergeyBerezovskiy 我目前有 query.GroupBy(x => x.randomId).Select(group => new { ID = group.Key }).ToList() 我在输出中得到重复的“randomId”值。此外,一瞥查询不显示 Distinct 或 group by
-
也许你认为值是重复的?例如。检查空格。 distinct 也应该存在于生成的查询中
-
看here: 使用 Select(new { Id = group.FirstOrDefault()} )
-
randomId 是一个数字列,因此我不能有空格并且查询仍然没有不同的。编辑帖子说我正在使用的 EF 版本!
标签: c# sql linq entity-framework group-by