考虑以下SQL查询:
<code class="language-sql">SELECT DISTINCT c.Id, c.Title, COUNT(v.Id) AS 'Nb_V2', COUNT(DISTINCT v.IdUser) AS 'Nb_V1', r.cnt AS 'Nb_R' FROM TABLE_C c JOIN TABLE_V v on c.Id = v.Id LEFT JOIN ( SELECT Id, COUNT(*) AS cnt FROM TABLE_R GROUP BY Id ) r ON c.Id = r.Id WHERE c.IdUser = '1234' GROUP BY c.Id, c.Title, r.cnt</code>
要将此SQL查询转换为LINQ查询表达式,请遵循以下准则:
GroupJoin
和DefaultIfEmpty()
模拟LEFT JOIN。应用这些规则会产生以下LINQ查询表达式:
<code class="language-csharp">var subrq = from r in Table_R group r by r.Id into rg select new { Id = rg.Key, cnt = rg.Count() }; var ansq = (from c in Table_C join v in Table_V on c.Id equals v.Id join r in subrq on c.Id equals r.Id into rj from r in rj.DefaultIfEmpty() where c.IdUser == "1234" group new { c, v, r } by new { c.Id, c.Title, r.cnt } into cvrg select new { cvrg.Key.Title, Nb_V2 = cvrg.Count(), Nb_V1 = cvrg.Select(cvr => cvr.v.IdUser).Distinct().Count(), Nb_R = (int?)cvrg.Key.cnt }).Distinct();</code>
对于lambda表达式转换,进一步将LEFT JOIN转换为GroupJoin...SelectMany
:
<code class="language-csharp">var subr2 = Table_R.GroupBy(r => r.Id).Select(rg => new { Id = rg.Key, cnt = rg.Count() }); var ans2 = Table_C.Where(c => c.IdUser == "1234") .Join(Table_V, c => c.Id, v => v.Id, (c, v) => new { c, v }) .GroupJoin(subr, cv => cv.c.Id, r => r.Id, (cv, rj) => new { cv.c, cv.v, rj }) .SelectMany(cvrj => cvrj.rj.DefaultIfEmpty(), (cvrj, r) => new { cvrj.c, cvrj.v, r }) .GroupBy(cvr => new { cvr.c.Id, cvr.c.Title, cvr.r.cnt }) .Select(cvrg => new { cvrg.Key.Title, Nb_V2 = cvrg.Count(), Nb_V1 = cvrg.Select(cvr => cvr.v.IdUser).Distinct().Count(), Nb_R = (int?)cvrg.Key.cnt });</code>
以上是如何有效地将具有多个联接和计数的复杂 SQL 查询转换为 LINQ?的详细内容。更多信息请关注PHP中文网其他相关文章!