代码之家  ›  专栏  ›  技术社区  ›  John Smith

活动记录查询不加载所有ID

  •  0
  • John Smith  · 技术社区  · 7 年前

    我有一个像这样的活动记录查询:

    House.where.not(id: Person.ill.pluck(:house_id))
    

    当我奔跑 explain 在这个查询中,我看到所有id都加载到查询中:

    Seq Scan on houses  (cost=0.00..4274.07 rows=1102 width=77)
     Filter: id <> ALL ('{1117,487,842,126,127,459,458,515,332,55,54,10,1697,449,448,1555,13,510,1986,8,9,7,6,5,1865,519,157,513,512,56,103,28,27,97,25,23,385,138,278,92,1,435,196,195,61,363,229,230,238,237,231,160,158,749,748,518,517,174,173,172,395,153,1170,207,206,276,199,198, ....
    

    是否有更多的穿孔方法来实现相同的查询?不加载所有的身份证?

    2 回复  |  直到 7 年前
        1
  •  3
  •   matthewd    7 年前

    pluck 立即运行查询,因为它返回一个id数组。

    你可以用 select 要将结果保留为一个关系,然后将其用作子查询:

    House.where.not(id: Person.ill.select(:house_id))
    
        2
  •  3
  •   taras    7 年前

    尝试使用 SQL JOIN ,但不能重复使用 ill 范围在这里。例如,如果此作用域如下所示:

    scope :ill, -> { where(status: 'ill') }
    

    那么您的查询可能是这样的:

    House.joins("JOIN persons ON houses.id = persons.house_id AND persons.status <> 'ill'")