LoginSignup
6
5

More than 3 years have passed since last update.

rails + mysql5.7で"Mysql2::Error: Expression #1 of ORDER BY clause is not in SELECT list, references column 'テーブル名.カラム名' which is not in SELECT list "

Posted at

環境

ruby 2.5.1
rails 5.2.4
mysql 5.7

背景

railsのDBをmysqlに変えて、rspecを実行したら、見慣れぬエラーが発生

ActionView::Template::Error:
   Mysql2::Error: Expression #1 of ORDER BY clause is not in SELECT list, references column
   'portfolio1_test.users.name' which is not in SELECT list; this is incompatible with DISTINCT:
    SELECT  DISTINCT `communities`.* FROM `communities` LEFT OUTER JOIN `community_users` ON
   `community_users`.`community_id` = `communities`.`id` LEFT OUTER JOIN `users` ON `users`.`id` = 
   `community_users`.`user_id` ORDER BY `users`.`name` DESC, created_at DESC LIMIT 15 OFFSET 0

原因

Mysqlから以下の設定が追加されたために問題が発生していたらしい
sql_mode,'ONLY_FULL_GROUP_BY

解決策1

上記の設定が影響するSQL文を変える
MySQL5.7にアップデートしたらonly_full_group_byでエラーになった

解決策2

Mysqlの設定を変える
Ransack の sort_link が MySQL で動作しない( incompatible with DISTINCT)

今回はMysqlの設定を変えることにした

変更する箇所が多すぎるので、Mysql の設定を変えることにした。
ローカルでは設定を変えることで、問題が解決するが、Docker 環境でもこの設定変更を実行させたい。

docker-compose.yml にて command を使って、設定を変更できるはず。

コンテナを構築する際に、Mysqlの設定を反映させたい

MySQL 5.7 のONLY_FULL_GROUP_BY が出た時にDockerでやった対処

docker-compose.yml
version: '3'
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    tty: true
    stdin_open: true
    depends_on:
      - db
    ports:
      - "3000:3000"
    volumes:
      - .:/myapp:delegated
  db:
    image: mysql:5.7
    command:
      - --sql-mode=NO_ENGINE_SUBSTITUTION   #追加!!
    environment:
      MYSQL_USER: root
      MYSQL_ROOT_PASSWORD: password
    ports:
      - '3316:3306'
    volumes:
      - ./db/mysql/volumes:/var/lib/mysql
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5