I’m using SQLite.
I need an help for an easy issue.
Here’s my three tables:
--------------
problem
--------------
id (primary key)
question_id (foreign key)
--------------
question
--------------
id (primary key)
answer_id (foreign key)
--------------
answer
--------------
id (primary key)
I would like to get ALL problems that have at least N answers in every question of a problem. I’ll give you an example:
-------
problem
id
1
2
-------
question
id problem_id
1 1
2 1
3 1
4 2
-------
answer
id question_id
1 1
2 1
3 1
4 2
5 2
6 3
7 4
8 4
If n=2, my result should be problem_id=2.
I’ve tried this:
select distinct question.problem_id
from answer, question
where answer.question_id = question.id
group by answer.question_id
having count(*) >= 2
but it doesn’t work because it gets problems with at least one question with at least 2 answers. All questions must satisfy that condition.
Any problems?
Here’s my go at the issue in T-SQL:
NB: the table schema differs slightly from the question as the schema in the question doesn’t match the example data.
ALTERNATIVE
(based on @RichardTheKiwi’s answer with the inner SQL moved to a temp table)