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:
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.