Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

My table has the following structure:

+----+---------+------------+-------------+
| id | word_id | meaning_id | sentence_id |
+----+---------+------------+-------------+
| 1  | 1       | 15333      | 1           |
| 2  | 1       | 12355      | 1           |
| 3  | 1       | 768        | 1           |
| 4  | 2       | 12455      | 1           |
| 5  | 2       | 9581       | 1           |
| 6  | 3       | 41         | 1           |
| 7  | 4       | 125        | 1           |
| 8  | 1       | 17854      | 2           |
| 9  | 2       | 35214      | 2           |
| 10 | 3       | 12455      | 2           |
| 11 | 3       | 988        | 2           |
+----+---------+------------+-------------+

I have a list of meaning_ids and I want to get all the sentence_ids that contain all of the meaning_ids. I do not care what the sentence it is, as long as the sentence contains all meaning_ids (= sentence_id is the same).

Lets say I have the following sentence_ids: 12455 and 15333. The query should return sentence_id 1 because both only occur there.

How can I achieve this with MySQL?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

This requirement is known as relational division. One popular approach is

SELECT sentence_id
FROM   YourTable
WHERE  meaning_id IN ( 12455, 15333 )
GROUP  BY sentence_id
HAVING COUNT(DISTINCT meaning_id) = 2 

SQL Fiddle

If your table has a unique constraint on sentence_id,meaning_id you can drop the DISTINCT in the query above.

share|improve this answer
2  
See also this similar question at SO which has more than 10 different ways (some will not work in mysql) to achieve relational division: How to filter SQL results in a has-many-through relation –  ypercube Mar 17 '13 at 12:43
    
It works! Thank you so much! –  Sophia Mar 17 '13 at 12:51
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.