chan

朝生暮死不足笑 但悲百年不足道

【MySQL】记录一个已解决但待深入的问题


mysql> select student.sid,sname from student left join score on student.sid = score.student_id group by student_id having count(1) = 1;
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘day27db.student.sid’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

上面是最初的SQL语句,报错。

下面是GPT的回答:

虽然 score.student_idstudent.sid 的外键,但 MySQL 不一定总能自动推断这种功能依赖性。当 ONLY_FULL_GROUP_BY 启用时,MySQL 会严格检查:

  • student.sidsname 是否在 GROUP BY 中。
  • 或是否通过聚合函数处理。

如果没有明确的功能依赖性,MySQL 会报错,因为它无法保证 student.sidsname 的值在分组中是唯一的。

可能的原因

MySQL 的版本和优化器行为可能不同。有些版本的优化器在某些情况下可以推断功能依赖性,而有些情况下不能。

优化器未能推断出功能依赖性

虽然外键约束建立了关联,但 GROUP BY score.student_id 并未直接包含 student.sid,而是通过外键间接关联的。

优化器可能认为这无法保证唯一性。

依赖版本或实现

更换主表及从表的位置后,正常运行。

select student.sid,sname from student left join score on student.sid = score.student_id group by student_id having count(1) = 1;

SELECT student.sid,student.sname FROM score LEFT JOIN student ON score.student_id = student.sid
GROUP BY student_id HAVING count( 1 ) =1;

至于表结构,如下图所示:

评论
还没有评论
    发表评论 说点什么