我有一个包含这两个表的数据库 - questions
和answers
。
表定义
questions - id, question, asked_by
answers - id, question_id(foreign key), answers, sent_by
我想计算并回应每个问题的答案总数。
示例数据
question
id question asked_by
1 how r u emma
2 r u ok sam
answer
id question_id answer sent_by
1 2 good john
2 1 fine sam
3 2 WTG biggie
在显示所有问题的页面上,我想按每个问题和答案数量编写。 question2= 2
和question1=1
的答案数。
答案 0 :(得分:0)
对于带有INNER JOIN
子句的每个问题,您应该使用COUNT
然后使用GROUP BY
条目:
SELECT t1.id
, COUNT(*)
FROM question t1
JOIN answer t2 ON t1.id = t2.question_id
GROUP BY t1.id
答案 1 :(得分:0)
首先尝试COUNT
,JOIN
,然后GROUP BY
SELECT q.question,count(*) AS answers FROM question q INNER JOIN answer a ON q.id=a.question.id
GROUP BY q.id