简体   繁体   中英

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. If you want the results wrapped in a model do something like this:

MyModel.find_by_sql("...")

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 " 
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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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