1

我有 group by 查询,在 PHP PDO 中运行良好,但是当我在 mysql ini 中添加“sql_mode = ONLY_FULL_GROUP_BY”时,相同的查询失败并出现错误

SQLSTATE[42000]:语法错误或访问冲突:1055 'db.table.t_date' 不在 GROUP BY 中

实际查询

SELECT 
    * 
FROM 
(
    SELECT 
        DATE_FORMAT(t_date, '%b') AS mon, 
        DATE_FORMAT(t_date, '%Y-%m') AS fy_date, 
        (SUM(val1) - SUM(val2)) AS net_val 
    FROM 
        TABLE 
    GROUP BY 
        YEAR(t_date), 
        MONTH(t_date) 
    ORDER BY 
        DATE_FORMAT(t_date, '%Y-%m') DESC 
    LIMIT 12
) AS tbl 
ORDER BY 
    fy_date

有人可以告诉为什么上面的查询不起作用

sql_mode = ONLY_FULL_GROUP_BY
4

1 回答 1

2

您需要将这两个date_format表达式都添加到 中,group by因为所有非聚合列都需要分组。

SELECT 
    DATE_FORMAT(t_date, '%b') AS mon, 
    DATE_FORMAT(t_date, '%Y-%m') AS fy_date, 
    (SUM(val1) - SUM(val2)) AS net_val 
FROM 
    TABLE 
GROUP BY 
    DATE_FORMAT(t_date, '%b'), 
    DATE_FORMAT(t_date, '%Y-%m') 
ORDER BY 
    DATE_FORMAT(t_date, '%Y-%m') DESC 
于 2012-09-15T11:42:20.470 回答