【问题标题】:Rails nested SQL with NOT IN condition带有 NOT IN 条件的 Rails 嵌套 SQL
【发布时间】:2012-11-08 08:07:45
【问题描述】:

我目前有这个代码:

class Group < ActiveRecord::Base
  has_many :roles

  #can't find better name for this method
  def self.without_role_ids
    find_by_sql('select id from groups where id not in
      (select distinct group_id from roles)').map { |g| g.id }
  end
end

class Role < ActiveRecord::Base
  belongs_to :group
end

without_role_ids 方法输出没有任何角色的组的 ID。

我想做的是重写这个方法:

def self.without_role_ids
  where("id NOT IN (?)", Role.pluck(:group_id))
end

它会产生两个查询。

可以运行

where(id: Role.select(:group_id))

它将只产生一个 SQL 查询,但使用 IN 而不是我需要的 NOT IN

是否可以在不使用 find_by_sql 的情况下通过一个查询来执行 NOT IN

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-3.2


    【解决方案1】:

    我找到了一个解决方案,用 Squeel 很容易执行这样的查询:

    https://github.com/ernie/squeel

    现在方法代码是:

    where{id.not_in Role.select(:group_id)}
    

    它会产生这个查询:

    SELECT "groups".* FROM "groups" WHERE "groups"."id" NOT IN
      (SELECT "roles"."group_id" FROM "roles" )
    

    有关于 Squeel 的 Railscast:http://railscasts.com/episodes/354-squeel

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多