在mysql中使用聚合函数时出错

时间:2018-07-24 06:33:22

标签: mysql sql

有两个表: 一种。黑客表:包含黑客ID和名称 b。提交表:包含提交ID,名称,挑战ID和分数。

用于以下查询:

SELECT
    a.hacker_id ,a.challenge_id, max(a.score) AS maxsc, b.name
FROM
    hackers as b
JOIN
    submissions AS a ON a.hacker_id = b.hacker_id
GROUP BY
    a.hacker_id, a.challenge_id

我收到此错误:

  

第10行的错误1055(42000):SELECT列表的表达式#2不在   GROUP BY子句,包含非聚合列   'run_nmouzxg94cx.b.name'在功能上不依赖于   GROUP BY子句中的列;这与   sql_mode = only_full_group_by

有人可以帮我吗?

3 个答案:

答案 0 :(得分:1)

您需要将name添加到分组条件中,或对其应用聚合函数-像这样:

select a.hacker_id, a.challenge_id, max(a.score) as maxsc, max(b.name) as name
from hackers as b 
join submissions as a on a.hacker_id=b.hacker_id 
group by a.hacker_id,a.challenge_id

有关sql_mode=only_full_group_by的更多信息:MySQL Handling of GROUP BY

答案 1 :(得分:0)

您的错误b.name也将包含在“ by by”子句中

 SELECT a.hacker_id, a.name,a.challenge_id, MAX(a.score) AS maxsc 
      FROM Submissions a
    inner join Hackers b
    on a.hacker_id=b.hacker_id
     GROUP BY a.hacker_id, a.name,a.challenge_id

答案 2 :(得分:0)

如果您希望分数最高的行,则可以执行以下操作:

SELECT s.hacker_id, s.challenge_id, s.score, h.name
FROM hackers h JOIN
     submissions s
     ON s.hacker_id = h.hacker_id
WHERE (s.challenge_id, s.score) IN 
          (SELECT s2.challenge_id, MAX(s2.score)
           FROM submissions s2
           GROUP BY s2.challenge_id
          );