H2数据库:列"U"必须在GROUP BY列表中; SQL 声明

H2 database: Column "U" must be in the GROUP BY list; SQL statement

我的本机查询如下所示:

SELECT u
FROM (SELECT max(difficulty), u
      FROM (SELECT sum(difficulty) AS difficulty, username AS u
            FROM user_answer ua
                     JOIN question q ON ua.question_id = q.id
                     JOIN answer a ON ua.answer_id = a.id
                     JOIN user_quiz uq ON ua.user_quiz_id = uq.id
                     JOIN account ac ON uq.account_id = ac.id
            WHERE a.correct = 1
              AND uq.quiz_start_date_time >= (CURDATE() - INTERVAL 7 DAY)
            GROUP BY ua.user_quiz_id
            ORDER BY difficulty DESC) AS max_week) as d_u

MySQL 一切正常。我在 H2 数据库中有一个错误:

org.h2.jdbc.JdbcSQLSyntaxErrorException: Column "U" must be in the GROUP BY list; SQL statement:
SELECT u FROM (SELECT max(difficulty), u FROM (SELECT sum(difficulty) AS difficulty, username AS u FROM user_answer ua JOIN question q ON ua.question_id = q.id JOIN answer a ON ua.answer_id = a.id JOIN user_quiz uq ON ua.user_quiz_id = uq.id JOIN account ac ON uq.account_id = ac.id WHERE a.correct = 1 AND uq.quiz_start_date_time >= (CURDATE() - INTERVAL 7 DAY) GROUP BY ua.user_quiz_id ORDER BY difficulty DESC) AS max_week) as d_u [90016-200]

如何解决?

简单的围绕用户名添加一个聚合函数

    SELECT u
    FROM (SELECT max(difficulty), u
          FROM (SELECT sum(difficulty) AS difficulty, MAX(username) AS u
                FROM user_answer ua
                         JOIN question q ON ua.question_id = q.id
                         JOIN answer a ON ua.answer_id = a.id
                         JOIN user_quiz uq ON ua.user_quiz_id = uq.id
                         JOIN account ac ON uq.account_id = ac.id
                WHERE a.correct = 1
                  AND uq.quiz_start_date_time >= (CURDATE() - INTERVAL 1 MONTH)
                GROUP BY ua.user_quiz_id
                ORDER BY difficulty DESC
            ) AS max_month
        GROUP BY u
        ) as d_u

启用选项 ONLY_FULL_GROUP_BY 后,您需要让所有列都具有聚合函数或将它们放在 GROUP 中 参见 https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html