与mysql中的sql_mode = only_full_group_by不兼容

时间:2016-12-28 05:03:32

标签: mysql ruby-on-rails

因此,在将项目从Rails 3.2升级到Rails 4.2时,不知怎的,我的一个模型中的查询看起来像:

rows = ActiveRecord::Base.connection.execute("Select q.id,q.times_taken,avg(qr.correct)*100,q.difficulty,q.weight,sk.name,sa.name,sub.name,q.tag_list from 
  (select qu.id,qu.times_taken,qu.difficulty,qu.weight,group_concat(tags.name) tag_list,qu.subject_id,qu.subject_area_id
    from questions qu left join taggings t on (qu.id = taggable_id) left join tags on (t.tag_id = tags.id) 
    where qu.id in (#{@questions_out_ids.join(',')}) and t.taggable_type='Question' group by t.taggable_id) q
  left join subjects sub on (q.subject_id = sub.id) left join subject_areas sa on (q.subject_area_id = sa.id) 
  left join skills_subject_areas ssa on (sa.id = ssa.subject_area_id) left join skills sk on (ssa.skill_id = sk.id), 
  archived_question_results qr,attempts a where  qr.question_id = q.id and a.id = qr.attempt_id and a.is_normalized = 1 
  and a.state = 'complete' group by qr.question_id order by q.id")

已经开始产生一个mysql错误,如下所示:

ERROR 1055 (42000): Expression #6 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'faces_development.sk.name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

我已经查看了类似问题的其他答案,我知道我需要在id子句中包含某个表的GROUP BY列,但是我的查询非常复杂,我尝试过的选择并没有多大用处。我正在使用gem mysql2 0.3.0建议?

3 个答案:

答案 0 :(得分:14)

config/database.yml

development: # Or test, or production, or all of them.
  ...
  variables:
    sql_mode: TRADITIONAL

答案 1 :(得分:1)

在您的config/database.yml文件中:

default: &default
  variables:
    sql_mode: TRADITIONAL

答案 2 :(得分:-1)

我认为我找到了解决问题的方法,显然是外6th中的select表达式,即sk.name产生了问题。将相同的表达式添加到外部group by子句中为我修复了它。

rows = ActiveRecord::Base.connection.execute("select q.id,q.times_taken,avg(qr.correct)*100,q.difficulty,q.weight,sk.name,sa.name,sub.name,q.tag_list from 
  (select qu.id,qu.times_taken,qu.difficulty,qu.weight,group_concat(tags.name) tag_list,qu.subject_id,qu.subject_area_id
    from questions qu left join taggings t on (qu.id = taggable_id) left join tags on (t.tag_id = tags.id) 
    where qu.id in (#{@questions_out_ids.join(',')}) and t.taggable_type='Question' group by t.taggable_id) q
  left join subjects sub on (q.subject_id = sub.id) left join subject_areas sa on (q.subject_area_id = sa.id) 
  left join skills_subject_areas ssa on (sa.id = ssa.subject_area_id) left join skills sk on (ssa.skill_id = sk.id), 
  archived_question_results qr,attempts a where  qr.question_id = q.id and a.id = qr.attempt_id and a.is_normalized = 1 
  and a.state = 'complete' group by sk.name, qr.question_id order by q.id")