NOT EXISTS rails 3.2中的SQL查询

时间:2013-09-23 04:44:08

标签: ruby-on-rails

我有一个像这样的SQL查询: -

SELECT * FROM `permissions` join entities where NOT EXISTS (select
 entity_id,permission_id from role_permissions where role_id=5 and 
 entities.id = role_permissions.entity_id and permissions.id = 
 role_permissions.permission_id)

我想获得相应的rails查询。

我试过这个。

Permission.joins("join entities").joins("LEFT OUTER JOIN role_permissions on 
 permission_id != permissions.id  and entities.id != entity_id and 
 role_permissions.role_id= role_id").select("role_permissions.entity_id,role_permissions.role_id,
 role_permissions.permission_id").group('role_permissions.entity_id,
 role_permissions.permission_id')

但它不起作用。

感谢 哈利

3 个答案:

答案 0 :(得分:1)

我最近特别喜欢EXISTS查询,正是因为它不需要你完全加入另一个表。据我所知,你必须显式编写SQL子句,但你仍然可以使它与Activerecord一起使用。你甚至可以将它放在lambda块中的范围内。

Permission.joins(:entities).where(<<-SQL
  NOT EXISTS(
    select
      * from role_permissions where role_id=#{your_role_id} and 
      entities.id = role_permissions.entity_id 
      and permissions.id = role_permissions.permission_id
  )
  SQL
)

答案 1 :(得分:0)

试试这个 根据第一评论更新

Permission.joins(:entities).joins("LEFT OUTER JOIN role_permissions on 
  permission_id != permissions.id  and entities.id != entity_id and 
  role_permissions.role_id= role_id")
  .select("role_permissions.entity_id,role_permissions.role_id,
   role_permissions.permission_id")
  .group('role_permissions.entity_id, role_permissions.permission_id')

答案 2 :(得分:0)

对于默认的SQL查询,请尝试这样做:

sql = "SELECT some_field FROM `permissions` join entities where NOT EXISTS (select entity_id,permission_id from role_permissions where role_id=5 and entities.id = role_permissions.entity_id and permissions.id = role_permissions.permission_id)"
results = ActiveRecord::Base.connection.execute(sql)
results.each do |result|
    @register_users << { some_field: result[0] }
end