2012-11-03 56 views
0

我跟隨查詢Rails的嵌套查詢

notes = Note.where('notes.id IN 
    (
    SELECT "notes"."id" FROM "notes" 
     WHERE "notes"."circle_id" = ? 
) 
    OR notes.id IN 
    (
    SELECT "notes"."id" FROM "notes" 
     INNER JOIN "circles_dreams" 
     ON "circles_dreams"."dream_id" = "notes"."dream_id" 
     WHERE "circles_dreams"."circle_id" = ? 
)', @circle.id, @circle.id) 

如何簡化這個查詢? 謝謝。

回答

0

首先你可以收集所有需要的筆記ID。 我應該以爲你已經有關係NoteCirclesDream之間

note_ids = Note.where(circle_id: @circle.id).pluck(:id) # your first SELECT 
dream_ids = CirclesDream.where(id: @circle.id).pluck(:note_id) # your second SELECT 

notes_ids = note_ids | dreams_ids # combine them 

notes = Note.where(id: notes_ids) # Now your 

UPD:我只是固定的錯字。在第二個請求

+0

「|」是「或」等效的? – lito

+0

@lito'> [1,2,3] | [1,4,5]#=> [1,2,3,4,5]' – ck3g

0

改變idnote_id試試這個

note_ids = Note.where('circle_id = ?', @circle.id).pluck(:id) 

dream_note_ids = Note.joins(:circle_dreams).where('circle_dreams.circle_id = ?', @circle.id).plunk(:note_id) 

notes_ids = note_ids | dream_note_ids 

如果您circle_dreams表可以包含具有note_id = null記錄,那麼你必須申請加入。所以我認爲這將適用於你的情況....