1

Ok. so I have 2 tables: questions and questions_answers

table 1 columns) question_text | question_id
table 2 columns) answer_text   | question_id

I want to perform a query that retrieves each row of questions with a count of the amount of answers that question has... So far I've come up with this:

SELECT *, (select count(*) from questions         
JOIN question_answers on question_answers.question_id =
questions.question_id) as answers from questions

However this query return the total number of answers of all the questions added. So if question 1 has 2 answers and question 2 has 3, this query returns 5 for all rthe questions. I want it to return the amount of answers each questions has. Any help??? Can´t seem to figure it out =(

This is what the query returns:

This is what the query returns =(

2 Answers 2

4
select  question_text 
,       count(qa.question_id) as answer_count
from    questions q
left join
        question_answers qa
on      qa.question_id = q.question_id
group by
        q.question_id
Sign up to request clarification or add additional context in comments.

1 Comment

select q.question_id, COUNT(qa.question_id) as answer_count from questions q left join question_answers qa on qa.question_id = q.question_id group by q.question_id (JUST CHANGED IT A BIT AND IT WORKED PERFECTLY!!! THANKS!)
2

Try this SQL query:

SELECT Q.question_id, COUNT(QA.question_id) as questions_cnt
FROM Questions AS Q
    LEFT JOIN Questions_answers AS QA ON Q.question_id = QA.question_id
GROUP BY Q.question_id

1 Comment

count(*) will return 1 for a question with no answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.