mysql - Searching for groups of rows where a column contains ALL given values -
i have table symptom_ratings containing columns id, user_id, review_id, symptom_id, rate, , strain_id.
each review can have multiple entries in symptom_ratings, 1 per symptom.
i search every strain_id has of symptom_id's user searches for.
that is, given columns:
review: 2, strain_id: 3, symptom_id: 43 review: 2, strain_id: 3, symptom_id: 23 review: 2, strain_id: 3, symptom_id: 12 review: 6, strain_id: 1, symptom_id: 3 review: 6, strain_id: 2, symptom_id: 12 searching symptom_id's 43 , 12 should return results strain_id 3.
i use following where condition:
strain.id in (select strain_id symptom_ratings symptom_id in ($symptoms)) where $symptoms comma-separated list of symptom_id values.
my problems query performs or search (i.e. finds strains have any of symptoms), instead i'd prefer , search (i.e. finding strains have all of symptoms). how can achieve that?
one way group rows strain id, count number of distinct matching symptoms in each group, , return rows count equals total number of symptoms searched for:
select strain_id, count(distinct symptom_id) matched_symptoms symptom_ratings symptom_id in (43, 12) group strain_id having matched_symptoms = 2 one potentially useful feature of method it's trivial extend support both "all of these", "any of these" , "at least n of these" searches changing condition in having clause. latter cases, can sort results number of matching symptoms (e.g. order matched_symptoms desc).
Comments
Post a Comment