gpt4 book ai didi

c# - 在 C# 中使用 group 和 join 进行 LINQ 查询

转载 作者:行者123 更新时间:2023-11-30 20:39:58 25 4
gpt4 key购买 nike

我试图在 LINQ C# 中编写以下 SQL 查询,但无法获取组子句后的列。

SQL查询

/*get the number of questions by subject*/

select b.SubjectID, b.SubjectName, count(*) AS count
from QuestionsTable a, SubjectTable b
where a.SubjectID is not null AND a.SubjectID = b.SubjectID
GROUP BY a.SubjectID

LINQ 查询

var result =(from a in db1.QuestionsTables
join b in db1.SubjectTables
on a.SubjectID equals b.SubjectID
where a.SubjectID != null
group a by a.SubjectID into g
select new { a.QuestionID, a.SubjectID, b.SubjectName
}).ToList();

最佳答案

您的 SQL 无法正确执行,因为您按 a.Subject.ID 查询组,但选择了 b.SubjectIDb.SubjectName。通常,您还应该将单个选定字段包含到 GROUP BY 列表中。

(据我所知,某些 SQL 服务器可以处理功能相关字段,因此它们可以处理您的查询。但通常这是错误的)。

所以你的工作查询应该是:

SELECT b.SubjectID, b.SubjectName, COUNT(*) AS Count 
FROM QuestionsTable a, SubjectTable b
WHERE a.SubjectID is not null AND a.SubjectID = b.SubjectID
GROUP BY b.SubjectID, b.SubjectName

你的 LINQ 应该是

from a in db.QuestionsTable
join b in db.SubjectTable
on a.SubjectId equals b.SubjectId
where a.SubjectId != null
group b by new { b.SubjectId, b.SubjectName } into g
select new { g.Key.SubjectId, g.Key.SubjectName, g.Count() }

关于c# - 在 C# 中使用 group 和 join 进行 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33866281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com