简体   繁体   English

如何创建Linq2Sql查询,该查询将对链接表中的记录进行分组并计算2个计数字段

[英]How to create Linq2Sql query that will group records from linked table and calculate 2 count fields

Here I found how to join tables using Linq2Sql and count amount of linked records LINQ - Left Join, Group By, and Count 在这里,我发现了如何使用Linq2Sql联接表并计算链接记录LINQ的数量-左联接,分组依据和计数

I've implemented it and it works ok for me: the following expression 我已经实现了它,对我来说效果很好:以下表达式

var v = from c in db.GetTable<Country>()
        join t0 in db.GetTable<Team>() on c.Id equals t0.CountryId into t1
        from team in t1.DefaultIfEmpty()
        group team by c.Id into teamsGrouped
        select new CountryTeamsInfo
            {
                CountryId = teamsGrouped.Key,
                TeamsTotal = teamsGrouped.Count(),
                // TeamsWithoutOwnerFree = teamsGrouped.Count(t => t.OwnerId==0)
            }
            ;
         List<CountryTeamsInfo> res = v.ToList();

generates the following query: 生成以下查询:

SELECT c.Id, Count(*) as c1
FROM countries c
LEFT JOIN teams t1 ON c.Id = t1.Country
GROUP BY c.Id 

In fact I need also to count those linker records that has OwnerId field non-equal to 0. 实际上,我还需要计算OwnerId字段不等于0的那些链接记录。

It looks like I should just uncomment that line in linq expression (TeamsWithoutOwnerFree = teamsGrouped.Count(t => t.OwnerId==0)), but that doesn't work, attempt to execute that causes an error: 看来我应该在linq表达式中取消注释该行(TeamsWithoutOwnerFree = teamsGrouped.Count(t => t.OwnerId == 0)),但这不起作用,尝试执行会导致错误:

The given key was not present in the dictionary 给定的键在字典中不存在

The query don't come to SQL log file, and I can't examine it in the debugger. 该查询不会进入SQL日志文件,并且我无法在调试器中对其进行检查。

What should be a proper way to count those lines from 'teams' table that meet additional criteria. 什么是从“团队”表计算符合附加条件的行的正确方法?

PS if it matters, I use C# 4.0, MySql 5.1 and BLToolkit 4.1 PS,如果有关系,我使用C#4.0,MySql 5.1和BLToolkit 4.1

Maybe try using GroupJoin() for your query: 也许尝试使用GroupJoin()进行查询:

var result = db.GetTable<Country>()
               .GroupJoin(db.GetTable<Team>(),
                   c => c.Id,
                   t => t.CountryId,
                   (country, teams) => new
                   {
                       CountryId = country.Id,
                       TeamsTotal = teams.Count(),
                       TeamsWithoutOwnerFree = teams.Count(t => t.OwnerId == 0)
                   })
               .ToList();

Due to RePierre help I was able to find the proper query: 由于RePierre的帮助,我得以找到正确的查询:

var v = db.GetTable<Country>().Where(country => country.Allowed)
                    .GroupJoin(
                        db.GetTable<Team>(),
                        country => country.Id,
                        team => team.CountryId,
                        (country, teams) => new CountryTeamsInfo
                                                {
                                                    CountryId = country.Id,
                                                    TeamsTotal = teams.Count(),
                                                    TeamsWithoutOwnerFree = teams.Count(t => t.OwnerId != 0),
                                                }
                    ).GroupJoin(
                        db.GetTable<Team>().Where(te=>te.OwnerId==0),
                        cti => cti.CountryId,
                        team => team.CountryId,
                        (cti, teams) => new CountryTeamsInfo
                        {
                            CountryId = cti.CountryId,
                            TeamsTotal = cti.TeamsTotal,
                            TeamsWithoutOwnerFree = teams.Count(t => t.OwnerId != 0),
                        }
                    )
                    ;

My concern is it uses 2 sub-queries... will try to optimize that. 我担心的是它使用2个子查询...将尝试对其进行优化。 Any ideas would be great 任何想法都很棒

PS Actually, generated SQL query looks ugly as well: PS实际上,生成的SQL查询看起来也很丑陋:

SELECT
cti.Id as Id1,
cti.c1 as c11,
(
    SELECT
        Count(*)
    FROM
        teams te
    WHERE
        cti.Id = te.Country AND te.User = 0
) as c2
FROM
(
    SELECT
        country.Id,
        (
            SELECT
                Count(*)
            FROM
                teams t1
            WHERE
                country.Id = t1.Country
        ) as c1
    FROM
        countries country
    WHERE
        country.allow

Here is query that works in my environment: 这是在我的环境中有效的查询:

from c in db.GetTable<Country>()
where c.Allowed
select new CountryTeamsInfo
{
    CountryId = c.Id,
    TeamsTotal = db.GetTable<Team>().Count(t => t.CountryId == c.Id && t.Allowed),
    TeamsHasOwner = db.GetTable<Team>().Count(t => t.CountryId == c.Id && t.Allowed && t.OwnerId != 0),
}

Not the best solution (I need to repeat teams selection criteria t.Allowed in each sub-query), but still works well and generated SQL is good. 不是最好的解决方案(我需要重复团队选择标准t。在每个子查询中都允许),但是仍然可以很好地工作,并且生成的SQL很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM