如何计算和回显价值

时间:2015-02-14 04:09:18

标签: mysql sql count

我有一个包含这两个表的数据库 - questionsanswers

表定义

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= 2question1=1的答案数。

2 个答案:

答案 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)

首先尝试COUNTJOIN,然后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