2017-08-08 91 views

回答

1

細節可能取決於你的數據庫,你創建的索引和數據存儲但我建議你給子查詢一試:

A.where.not(id: B.select(:a_id)) 

在PostgreSQL的,這將導致像單查詢

SELECT * FROM as WHERE id NOT IN (SELECT a_id FROM bs) 
+0

Th正是我所需要的!我們很快就會接受答案。謝謝 –

+0

謝謝@RonanLopes!如果查詢結果太慢,請發佈更新,我很樂意幫助您調整它。 :-) –

3

由於導軌5的:

A.left_outer_joins(:bs).where(bs: { a_id: nil }) 

的在SQL的輸出爲:

SELECT "as".* FROM "as" 
LEFT OUTER JOIN "bs" ON "bs"."a_id" = "a"."id" 
WHERE "bs.a_id" IS NULL 
+0

這裏的基準https://stackoverflow.com/a/45574301/2009803 – olimart

0

我在想你你的模型看起來像

class A < ApplicationRecord 
    has_may :bs 
end 

class B < ApplicationRecord 
    belongs_to :a 
end 

我想到你的schema.rb看起來像

create_table "as", force: :cascade do |t| 
    t.integer "id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "bs", force: :cascade do |t| 
    t.integer "id" 
    t.integer "a_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

,如果我有這那麼你應該可以做

A.where.not(id: B.select(:a_id))