For example this query:
SELECT `variants`.*
FROM `variants` INNER JOIN `variant_attributes`
ON variant_attributes.variant_id = variants.id
WHERE (variant_attributes.id IN ('2','5'))
And variant has_many variant_attributes
What I actually want to do is to find which variant has BOTH variant attributes with ID = 2 and 5. Is this possible with MySQL? Bonus Question, is there a quick way to do this with Ruby on Rails, perhaps with SearchLogic?
solution
Thank you Quassnoi for the query you provided, that worked perfectly.
To use on Rails, I used the named_scope below, I think this is simpler to understand for beginners.
Basically named_scope would return {:from => x, :conditions => y} and the lines above were used to setup the y variable.
named_scope :with_variant_attribute_values, lambda { |values|
conditions = ["(
SELECT COUNT(*)
FROM `variant_attributes`
WHERE variant_attributes.variant_id = variants.id
AND variant_attributes.value IN (#{values.collect { |value| "?" }.join ", "})
) = ?
"]
conditions = conditions + values + [values.length]
{
:from => 'variants',
:conditions => conditions
}}