Question

I have follow query

  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)

How to simplify this query? Thanks.

Was it helpful?

Solution

First of all you can collect all needed notes id. I supposed to think what you already have relations between Note and CirclesDream

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: I've just fixed typo. Changed id to note_id in second request

OTHER TIPS

Try this

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

If your circle_dreams table can contain records having note_id = null, then you have to apply join. So i think this will work in your case....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top