0

我在 Ruby 中有以下代码:

Comment.select("comments.*, COALESCE(SUM(votes.value), 0) AS rating,
  user_votes.value AS user_value").
  joins("LEFT JOIN votes ON votes.voteable_type = '"+type+"' AND votes.voteable_id = comments.id").
  joins("LEFT JOIN votes AS user_votes ON user_votes.voteable_type = '"+type+"' AND user_votes.voteable_id = comments.id AND user_votes.user_id = #{user_id}").
  where(conditions).group("comments.id").order("comments."+method).limit(limit).offset(offset)

当 Rails 生成这个 SQL 查询时,它不包括完整的 select 语句:

SELECT COUNT(*) AS count_all, comments.id AS comments_id FROM `comments`
LEFT JOIN votes ON votes.voteable_type = 'reply' AND votes.voteable_id = comments.id 
LEFT JOIN votes AS user_votes ON user_votes.voteable_type = 'reply' AND 
user_votes.voteable_id = comments.id AND user_votes.user_id = 1 WHERE (commentable_id = 
1 AND commentable_type = 'Impression')
GROUP BY comments.id ORDER BY comments.rating DESC LIMIT 10 OFFSET 0

但是,如果我删除了 group 语句,那么它会正确地包含完整的 select 语句。这是怎么回事?

4

1 回答 1

1

select comments.* 在您的 select 语句中与 group by("comments.id") 冲突。

选择的每一列必须要么在 GROUP BY 子句中,要么包含在聚合函数中。

SQL Server 显示 SQL 错误:select c.* from tt_country c group by c.name

列“tt_country.country_id”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

ActiveRecord 和 arel 抛出指定的选择,因为它不明确/无效。

于 2013-08-08T22:18:00.010 回答