4

我有一个带有“Clicks”表的 MySQL 数据库。有一个“已创建”列(日期时间),我想对其进行分组并选择年、月和日部分。我想计算特定日期范围(startDate 和 endDate)内每天的记录。

var query = from c in scope.Entities.Clicks  
                where c.Created >= startDate && c.Created <= endDate  
                group c by new {c.Created.Year, c.Created.Month, c.Created.Day}  
                into grouped     
                select new  {  
                                Year = grouped.Key.Year,  
                                Month = grouped.Key.Month,  
                                Day = grouped.Key.Day,  
                                Clicks = grouped.Count()  
                            };  

这会产生一个错误的查询:

SELECT
`GroupBy1`.`K1` AS `C1`,  
`GroupBy1`.`K2` AS `C2`,  
`GroupBy1`.`K3` AS `C3`,  
`GroupBy1`.`K4` AS `C4`,  
`GroupBy1`.`A1` AS `C5` 
FROM (SELECT  
COUNT(1) AS `A1`  
FROM `Click` AS `Extent1`  
 WHERE (`Extent1`.`Created` >= @p__linq__0) AND (`Extent1`.`Created` <= @p__linq__1)  
 GROUP BY   
1,   
YEAR(`Extent1`.`Created`),   
MONTH(`Extent1`.`Created`),   
DAY(`Extent1`.`Created`)) AS `GroupBy1`  

出现错误:MySql.Data.MySqlClient.MySqlException: Can't group on 'A1'

我做错了什么?或者这是一个 MySql 连接器错误?我尝试了 MySQL 连接器 6.5.4 和 6.6.5

4

1 回答 1

3

DJ KRAZE 我尝试了你的方法,结果证明必须使用双重“选择”才能通过 EF 生成正确的查询。谢谢!如果有人需要,我会在此处发布完整答案。

我测试了两种方式并且都有效:

    var subQuery = from c in scope.Entities.Clicks
                   where c.Created >= startDate && c.Created <= endDate
                   select new { c.Created.Year, c.Created.Month, c.Created.Day };

    var query = from c in subQuery
                group c by new {c.Year, c.Month, c.Day}
                into grouped
                select new {
                             Year = grouped.Key.Year,
                             Month = grouped.Key.Month,
                             Day = grouped.Key.Day,
                             Clicks = grouped.Count()
                           };

var query = scope.Entities.Clicks.Where(c => c.Created >= startDate && c.Created <= endDate)
      .Select(c => new { c.Created.Year, c.Created.Month, c.Created.Day})
      .GroupBy(c => new {c.Year, c.Month, c.Day})
      .Select(grouped => new { Clicks = grouped.Count(), grouped.Key.Year, grouped.Key.Month, grouped.Key.Day});

这些给出了正确的mysql查询:

SELECT
1 AS `C1`, 
`GroupBy1`.`K1` AS `C2`, 
`GroupBy1`.`K2` AS `C3`, 
`GroupBy1`.`K3` AS `C4`, 
`GroupBy1`.`A1` AS `C5`
FROM (SELECT
`Project1`.`C1` AS `K1`, 
`Project1`.`C2` AS `K2`, 
`Project1`.`C3` AS `K3`, 
COUNT(1) AS `A1`
FROM (SELECT
YEAR(`Extent1`.`Created`) AS `C1`, 
MONTH(`Extent1`.`Created`) AS `C2`, 
DAY(`Extent1`.`Created`) AS `C3`
FROM `Click` AS `Extent1`
 WHERE (`Extent1`.`Created` >= @p__linq__0) AND (`Extent1`.`Created` <= @p__linq__1)) AS `Project1`
 GROUP BY 
 `Project1`.`C1`, 
 `Project1`.`C2`, 
 `Project1`.`C3`) AS `GroupBy1`

(我仍然认为这是一个错误,我的第一个查询应该也可以正常工作)

于 2013-03-08T00:01:29.020 回答