简体   繁体   English

Rails 3 ActiveRecord:UNION

[英]Rails 3 ActiveRecord: UNION

有没有办法在Rails 3中使用MySQL UNION?

I think the only way you're going to get this to work by directly executing the query. 我认为你通过直接执行查询来实现这一目标的唯一方法。

ActiveRecord::Base.connection.execute("SELECT REPEAT('a',1) UNION SELECT REPEAT('b',10)")

This returns an ActiveRecord resultset. 这将返回ActiveRecord结果集。 If you want the results wrapped in a model do something like this: 如果您希望包含在模型中的结果执行以下操作:

MyModel.find_by_sql("...")

I found a neat hack using select . 我找到了一个使用select的整洁黑客。 For example if you want to make a union between User and OtherUser . 例如,如果要在User和OtherUser之间建立联合。

User.select('id from other_users union select id')

this will generate this SQL 这将生成此SQL

"SELECT id from other_users union select id FROM users " 
Model.find_by_sql("your union query")

As you can read on this thread there are people working on a better solution for creating union queries in Rails: 正如您可以在此主题上阅读的那样,有人正在研究在Rails中创建联合查询的更好解决方案:

https://github.com/rails/arel/pull/118 https://github.com/rails/arel/pull/118

Meanwhile, I have written an small hack with which you'll be able to create simple union queries and do some filters with DISTINCT, ORDER BY and LIMIT: 同时,我编写了一个小的hack,你可以使用它来创建简单的联合查询,并使用DISTINCT,ORDER BY和LIMIT进行一些过滤:

http://coderwall.com/p/9hohaa http://coderwall.com/p/9hohaa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM