Rails / activerecords - 分组依据和排序依据

时间:2012-04-06 14:05:55

标签: ruby-on-rails activerecord

我想在我的模块上执行:group:order,因为Mysql按顺序分组,你会得到混合结果而不是你期望的结果。

SQL的解决方案是:

SELECT * FROM 

(
select * from `my_table` order by timestamp desc
) as my_table_tmp

group by catid

order by nid desc

如何使用activerecord在ruby中编写?

2 个答案:

答案 0 :(得分:2)

我认为您可以直接使用Arel方法:

MyTable.from("(SELECT * FROM my_table ORDER BY timestamp DESC) as my_table").group(:catid).order("nid DESC")

答案 1 :(得分:0)

query = <<-sql_statement

  SELECT * FROM 

  (
  select * from `my_table` order by timestamp desc
  ) as my_table_tmp

  group by catid

  order by nid desc

sql_statement

result = MyTable.connection.execute(query)

您也可以使用ActiveRecord::Base.connection.execute(query)

要遍历返回的记录,请使用result.each

示例(来自mysql2 gem repo):

results.each do |row|
  # conveniently, row is a hash
  # the keys are the fields, as you'd expect
  # the values are pre-built ruby primitives mapped from their corresponding field types in MySQL
  # Here's an otter: http://farm1.static.flickr.com/130/398077070_b8795d0ef3_b.jpg
end