Rails 3 ActiveRecord: UNION

孤街醉人 提交于 2019-12-10 12:53:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!