Mysql Rails如何在实例不存在的情况下查询有多个实例

Mysql Rails如何在实例不存在的情况下查询有多个实例,mysql,sql,ruby-on-rails,ruby-on-rails-4,Mysql,Sql,Ruby On Rails,Ruby On Rails 4,请帮忙 我需要将下面的查询子句合并为一个 Foo.where('bar_id IS NULL') Foo.joins(:bar).where('bar.daily_budget > bar.daily_cost') 当在子句中连接(:bar)时,bar\u id为空记录将被过滤 Foo.joins(:bar).where('bar.daily_budget > bar.daily_cost').where('bar_id IS NULL') 下面这样组合并不是那么简单,这个bar

请帮忙

我需要将下面的查询子句合并为一个

Foo.where('bar_id IS NULL')
Foo.joins(:bar).where('bar.daily_budget > bar.daily_cost')
在子句中连接(:bar)
时,
bar\u id为空
记录将被过滤

Foo.joins(:bar).where('bar.daily_budget > bar.daily_cost').where('bar_id IS NULL')
下面这样组合并不是那么简单,这个
bar\u id为空将被过滤

Foo.joins(:bar).where('bar.daily_budget > bar.daily_cost').where('bar_id IS NULL')
我想要的结果更像

bar_id is null or (bar_id is not null AND bars.daily_budget > bars.daily_cost)

Foo结果需要bar\u id为空,如果bar同时存在,则bars.daily\u budget>bars.daily\u cost。

您实际需要的是SQL UNION

您可以使用
#或
查询方法。诀窍是,对于传递给#的关系,您必须在两端使用
连接(:bar)
,或者必须在结构上兼容

注意:在Rails 5中添加了QueryMethod

更新:正如DanneManne回答的那样,上面的操作不起作用,因为
.JOIN(:bar)。where(:bar\u id=>nil)
实际上不会给出任何关于内部连接的信息。所需的是左连接,可通过以下方式完成:

Foo.left_outer_joins(:bar).where('foo.bar_id is null or bar.daily_budget > bar.daily_cost')
SELECT `foos`.* from `foos` LEFT OUTER JOIN `bar` ON `foos`.`bar_id` = `bar`.`id` WHERE (foo.bar_id is null or bar.daily_budget > bar.daily_cost)

调用
.joins(:bar)
的问题是,默认情况下,它将创建一个
内部联接
数据库查询。当这种情况发生时,
bar\u id
为空的记录将不包括在结果中。并且指定
where(bar\u id:null)
不会改变这一点

但是,您可以通过将
左外部联接
字符串传递给
联接
方法(而不是符号)来解决此问题,然后从那里开始工作。例如:

Foo.joins('LEFT OUTER JOIN bar ON foo.bar_id = bar.id')
   .where('foo.bar_id IS NULL OR bar.daily_budget > bar.daily_cost')

请注意,您案例中的表名最有可能是复数,因此请确保查询与您的环境匹配。

joins
在Rails中是
内部JOIN

您需要的是
外部联接

,但是
Foo.joins(:bar)。其中(bar\u id:nil)
不兼容。过滤
where(:bar\u id=>nil)
结果。我在控制台中尝试了
Foo.where(bar\u id:nil).或(Foo.joins(:bar).where('bar.daily\u budget>bar.daily\u cost')
,然后我得到了这些错误
ArgumentError:传递给#的关系,或者必须在结构上兼容。不兼容的值:[:joins]
。请尝试
Foo.left\u outer\u joins(:bar)。其中('Foo.bar\u id为null或bar.daily\u budget>bar.daily\u cost')
感谢您提及
left outer JOIN
,它的工作原理。但是@kiddorail的答案较短
Foo.left\u outer\u连接(:bar)