0

我想在我的模块上执行:group和执行:order,因为 Mysql 确实在 order by 之前进行分组,你会得到混合的结果,而不是你所期望的。

对此的 SQL 解决方案是:

SELECT * FROM 

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

group by catid

order by nid desc

如何使用 activerecord 在 ruby​​ 中编写它?

4

2 回答 2

1

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

MyTable.from("(SELECT * FROM my_table ORDER BY timestamp DESC) as my_table").group(:catid).order("nid DESC")
于 2012-04-06T14:37:44.473 回答
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
于 2012-04-06T14:14:16.550 回答