2016-09-02 3 views
0

이 같은 범위가있다.동일한 테이블에 합류 할 때 Rails의 집계 계산으로 어떻게 정렬합니까? 이 SQLite는 잘 완벽하게 작동하지만, MySQL의 실패</p> <pre><code>scope :sorted_by_dongle_count, > { includes(:dongles) .order('count(dongles.id) ASC') .group('organisations.id') .references(:dongles) } </code></pre> <p>:

SELECT `organisations`.`id` AS t0_r0, 
     `organisations`.`name` AS t0_r1, 
     `dongles`.`id` AS t1_r0,   This should be an aggregate! 
     `dongles`.`name` AS t1_r1, 
     `dongles`.`organisation_id` AS t1_r4 
FROM `organisations` 
    LEFT OUTER JOIN `dongles` 
    ON `dongles`.`organisation_id` = `organisations`.`id` 
GROUP BY organisations.id 
ORDER BY count(dongles.id) DESC 

(선택 의지하지 않고이 작업을 수행 할 수있는 적절한 방법이 있나요)과의 전체 목록을 하드 코딩 : 쿼리를 보면

ActiveRecord::StatementInvalid: Mysql2::Error: Expression #8 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'portal_development.dongles.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by: [query here]

, 이유 을 쉽게 알 수있다 열?

답변

0

내가 발견 (내가 이미 알고 또 다른 해결 방법은 카운트 캐싱 내가 정렬을 가속화 할 쉽게 사용할 수를 가진 것으로, 이미 고려하고있다..) 그 전으로 변경하는 경우 :

scope :sorted_by_dongle_count, 
    -> { joins(:dongles)  
      .order('count(dongles.id) ASC') 
      .group('organisations.id') 
      .references(:dongles) } 

나는 오류를 멈추고 결과는 동일했다. 그래서 카운트 나 다른 집계를 사용할 때만 includes을 사용하지 마십시오. 다른 검색어의 경우 includes ...

을 사용하십시오.