ActiveRecord的相当于SQL'减' [英] activerecord equivalent to SQL 'minus'
问题描述
什么是轨道的方式减去从另一个查询结果?数据库特定的SQL的例子是:
从Store_Information选择日期
减去
从Internet_Sales选择日期
我会扔这到混合 - 不是一个解决办法,但可能有助于进展:
最好的我能想到的是,不要使用:
StoreInformation.where('日NOT IN(?)',InternetSale.all)
这是Rails的3 - 轨道2将是:
StoreInformation.all(:条件=> ['?日期NOT IN()',InternetSale.all])
不过,这两个都会首先选择了从internet_sales;你真正想要的是一个嵌套查询做整个事情的数据库引擎。对于这一点,我认为你必须要打入的find_by_sql,只是给一个嵌套查询。
显然,这种假设你使用MySQL! HTH。
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
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.
这篇关于ActiveRecord的相当于SQL'减'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!