问题
Is there any way to use MySQL UNION in Rails 3?
回答1:
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. If you want the results wrapped in a model do something like this:
MyModel.find_by_sql("...")
回答2:
I found a neat hack using select . For example if you want to make a union between User and OtherUser .
User.select('id from other_users union select id')
this will generate this SQL
"SELECT id from other_users union select id FROM users "
回答3:
Model.find_by_sql("your union query")
回答4:
As you can read on this thread there are people working on a better solution for creating union queries in Rails:
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:
http://coderwall.com/p/9hohaa
来源:https://stackoverflow.com/questions/5583471/rails-3-activerecord-union