activerecord equivalent to SQL 'minus'

南楼画角 提交于 2019-12-10 16:53:07

问题


What's the rails way to subtract a query result from another? A database specific SQL example would be:

SELECT Date FROM Store_Information
MINUS
SELECT Date FROM Internet_Sales 

回答1:


I'll throw this into the mix - not a solution, but might help with the progress:

Best I can think of is to use NOT IN:

StoreInformation.where('date NOT IN (?)', InternetSale.all)

That's Rails 3 - Rails 2 would be:

StoreInformation.all(:conditions => ['date NOT IN(?)', InternetSale.all])

But both of these will first select everything from internet_sales; what you really want is a nested query to do the whole thing in the database engine. For this, I think you'll have to break into find_by_sql and just give a nested query.

Obviously this assumes you're using MySQL! HTH.




回答2:


Late answer but I think you meant :

activities = Activity.all

searches = activites.where(key: 'search')

(activites - searches).each do |anything_but_search|
   p anything_but_search
end

You can substract two ActiveRecordsRelation and get the MINUS result, just like SQL would.

I am using Rails 4.2 so anything beyond that version should do the trick.



来源:https://stackoverflow.com/questions/3428852/activerecord-equivalent-to-sql-minus

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