Select 使用连接和分组进行计数

Select count with join and group by

我的代码中有 linq 查询,它没有给出正确的输出。 我有两个 Mysql 表 "classes" 和 "eleves",它们具有 1-n 关系。这是查询:

from p in db.Classes
from e in db.Eleves.LeftJoin(el => el.Classe == p.IdC)
group e by p.IdC into _
select new Classe{IdC=_.Key, Num=_.Count()}

它生成这个 SQL 语句:

SELECT
`t2`.`id_c`,
Count(*) as `c1`
FROM
`classe` `t2`
    LEFT JOIN `eleve` `t1` ON `t1`.`classe` = `t2`.`id_c`
GROUP BY
`t2`.`id_c`

输出这个结果:

乍一看,我认为这很好。但是我注意到 "classes" 和 no "eleves",也在 "cl" 列中输出“1”。当我像这样编辑 SQL 语句时:

SELECT
`t2`.`id_c`,
Count(matricule) as `c1`
FROM
`classe` `t2`
    LEFT JOIN `eleve` `t1` ON `t1`.`classe` = `t2`.`id_c`
GROUP BY
`t2`.`id_c`

这是预期的输出。 谷歌搜索后,我无法弄清楚如何格式化查询以获得正确的输出。 我尝试了很多这样的建议

from p in db.Classes
from e in db.Eleves.LeftJoin(el => el.Classe == p.IdC)
group e by p.IdC into _
select new Classe { IdC = _.Key, elv = _.Count(u=>u.Matricule!=null) }

from p in db.Classes
from e in db.Eleves.LeftJoin(el => el.Classe == p.IdC)
group e by p.IdC into _
select new Classe { IdC = _.Key, elv = _.Select(x => x.Matricule).Distinct().Count() }

但我收到错误消息“LinqToDB.LinqToDBException:‘'u.Matricule' 无法转换为 SQL。” “

我最终找到了一个给出正确输出的查询:

from p in db.Classes
join e in db.Eleves on p.IdC equals e.Classe into k
select new Classe { IdC = p.IdC, elv = k.Count()}

生成此 SQL 语句:

SELECT
`p`.`id_c`,
(
    SELECT
        Count(*)
    FROM
        `eleve` `t1`
    WHERE
        `p`.`id_c` = `t1`.`classe`
) as `c1`
FROM
`classe` `p`

但我不知道这是否是处理此问题的优化方式。 你能给我建议吗?

使用以下 LINQ 查询:

from p in db.Classes
from e in db.Eleves.LeftJoin(el => el.Classe == p.IdC)
group e by p.IdC into _
select new Classe 
{ 
    IdC = _.Key, 
    elv = _.CountExt(u => u.Matricule, Sql.AggregateModifier.Distinct) 
}