Pertimbangkan pertanyaan SQL berikut:
<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>
Untuk menukar pertanyaan SQL ini kepada ungkapan pertanyaan LINQ, sila ikut garis panduan ini:
GroupJoin
dan DefaultIfEmpty()
untuk mensimulasikan LEFT JOIN. Menggunakan peraturan ini menghasilkan ungkapan pertanyaan LINQ berikut:
<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>
Untuk penukaran ungkapan lambda, tukarkan LEFT JOIN kepada 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>
Atas ialah kandungan terperinci Bagaimana Menerjemahkan Pertanyaan SQL Kompleks dengan Cekap dengan Gabungan Berbilang dan Kiraan ke dalam LINQ?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!