繁体   English   中英

“不输入”以进行有效记录

[英]“NOT IN” for Active Record

我有一个MySQL查询,该查询试图在其末尾链接“ NOT IN”。

这是使用Active Record在红宝石中的外观:

not_in = find_by_sql("SELECT parent_dimension_id FROM relations WHERE relation_type_id  = 6;").map(&:parent_dimension_id)

      joins('INNER JOIN dimensions ON child_dimension_id = dimensions.id')
          .where(relation_type_id: model_relation_id,
                 parent_dimension_id: sub_type_ids,
                 child_dimension_id: model_type)
          .where.not(parent_dimension_id: not_in)

因此,我尝试执行的SQL查询如下所示:

INNER JOIN dimensions ON child_dimension_id = dimensions.id
WHERE relations.relation_type_id = 5 
AND relations.parent_dimension_id 
NOT IN(SELECT parent_dimension_id FROM relations WHERE relation_type_id  = 6);

有人可以向我确认该查询应使用什么吗? 我要在哪里挂链吗?

如果你真的想要

SELECT parent_dimension_id
FROM relations
WHERE relation_type_id = 6

作为子查询,您只需要将该SQL转换为ActiveRecord关系:

Relation.select(:parent_dimension_id).where(:relation_type_id => 6)

然后将其用作where调用中的值,就像使用数组一样:

not_parents = Relation.select(:parent_dimension_id).where(:relation_type_id => 6)

Relation.joins('...')
        .where(relation_type_id: model_relation_id, ...)
        .where.not(parent_dimension_id: not_parents)

当您将ActiveRecord关系用作where的值并且该关系选择单个列时:

r = M1.select(:one_column).where(...)
M2.where(:column => r)

ActiveRecord足够聪明,可以将r的SQL作为in (select one_column ...)内联in (select one_column ...)而不是执行两个查询。

您可能可以替换您的:

joins('INNER JOIN dimensions ON child_dimension_id = dimensions.id')

如果还建立了关系,则使用一个更简单的joins(:some_relation)

您可以为where子句提供值或值数组,在这种情况下,它们将被翻译成in (?)子句。

因此,查询的最后一部分可能包含一个映射:

.where.not(parent_dimension_id:Relation.where(relation_type_id:6).map(&:parent_dimension_id))

或者您可以准备一份声明

.where('parent_dimension_id not in (?)', Relation.where(relation_type_id:6).map(&:parent_dimension_id) )

本质上是完全一样的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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