0

我在heredoc中有这个简单的SQL

sql = <<-SQL
  SELECT SUM(price) as total_price, 
    SUM(distance) as total_distance, 
    TO_CHAR(date, 'YYYY-MM') as month
  FROM Rides
  WHERE user_id = #{current_user.id}
  GROUP_BY month
SQL

和一个find_by_sql(sql)电话

Ride.find_by_sql(sql).each do |row|
  "#{row.month}: { total_distance: #{row.total_distance}, total_price: #{row.total_price} }" 
end

它会引发错误:

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "GROUP_BY"
LINE 6:         GROUP_BY month
                ^
:         SELECT SUM(price) as total_price, 
          SUM(distance) as total_distance, 
          TO_CHAR(date, 'YYYY-MM') as month
        FROM Rides
        WHERE user_id = 1
        GROUP_BY month

如您所见,它对 user_id 进行了很好的插值,因此问题不在于插值。

如果我将此 SQL 作为字符串分配给变量,它会起作用,如下所示:

str = "select sum(distance) as total_distance, sum(price) as total_price, to_char(date, 'YYYY-MM') as month from rides where user_id = #{ current_user.id } group by month"

heredoc有什么问题?

4

1 回答 1

1

SQL 有一个GROUP BY子句 not GROUP_BY

sql = <<-SQL
  SELECT SUM(price) as total_price, 
    SUM(distance) as total_distance, 
    TO_CHAR(date, 'YYYY-MM') as month
  FROM Rides
  WHERE user_id = #{current_user.id}
  GROUP BY month
SQL
于 2018-11-16T15:22:05.603 回答