Ted
Ted

Reputation: 4166

sql select with count condition

I have 2 tables in my DB, first table called "questions" and hold questions with id, second table called "answers" and hold answers for the questions (as multiple choices).

how to select questions that have less than 4 answers?

questions table:

id     question
1      what is ...?
2      how many ...?
3      Is ....?

answers table

id     question_id     answer
1          1             54
2          1             11
3          1             22
4          2            England
5          1              5
6          2            Turkey

how to select questions that have answers less than 4?

thanks,

Upvotes: 0

Views: 64

Answers (2)

ah_hau
ah_hau

Reputation: 768

select questions.id, questions.question from questions 
inner join answers on questions.id = answers.question_id
group by questions.id, questions.question having count(questions.id) <4

here you go.

Upvotes: 3

Farrokh
Farrokh

Reputation: 1167

use this :

SELECT * 
FROM questions 
WHERE id in
    (
    SELECT question_id 
    from answers 
    group by question_id 
    having count(question_id) <4
    )

Upvotes: 0

Related Questions