In a rails 3 app I’m building I have these three classes:
class Instrument < ActiveRecord::Base
has_many :parts
has_many :pieces, through: :parts
end
class Part < ActiveRecord::Base
belongs_to :instrument
belongs_to :piece
end
class Piece < ActiveRecord::Base
has_many :parts
has_many :instruments, through: :parts
end
I am looking for a way to select all Pieces of which the associated instruments are a subset of an arbitrary set of instruments.
To avoid confusion I’ll give an example: given
- Piece(id:1) with instruments: [1,2,3],
- Piece(id:2) with [1,2,3,4]
- Piece(id:3) with [1,3,4]
- Piece(id:4) with [2],
somequery(1,2,3,4) should yield all four pieces, somequery(1,2,3) only 1 and 4, somequery(1,3,4) only piece 3 and somequery(2) only 4.
I’m using rails 3.2 and a solution in rails would be great but sql is also fine, and preferably postgres, but if there is a mysql-specific solution to this that would also be fine. Furthermore I’m not working with a relatively small database (1000+ pieces, 50 instruments and 15.000 parts) which isn’t heavily queried, so if the query is not optimal in efficiency that is no problem.
As a final disclaimer, I know my way around in ruby/rails, but am fairly green in SQL.
Thanks for the help!
The pure sql (not the double negation
NOT EXISTS , NOT IN():