我在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语句。发生了什么事?
答案 0 :(得分:1)
选择语句中的注释。*与group by(“comments.id”)冲突。
所选的每列必须位于GROUP BY子句中,或者包含在聚合函数中。
SQL Server显示SQL错误: 通过c.name
从tt_country c group中选择c。*列'tt_country.country_id'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
ActiveRecord和arel会抛出指定的select,因为它不明确/无效。