我正在计算答案,我不知道该如何自动化

时间:2019-09-30 09:49:52

标签: php mysql select

我有一个数据库的答案,我现在可以数1,但是我想显示选择答案的次数。我不知道该怎么做。 例如,我想计算在“ question_id”(问题)中回答“ answer_id”(答案的ID)1和2的次数

我尝试在上面设置一个不同的值,但这对我来说不起作用。The database

<?php  
$conn = mysqli_connect('localhost', 'root','','survey_cms_4people');
if (!$conn){
    echo "DATABSE ERROR!";
}

$variable = 1;
$countAnswerQuery = "SELECT COUNT(`answer_id`) FROM survey_answers WHERE question_id=$variable AND answer_id=$variable ";
$countanswerresult = mysqli_query($conn, $countAnswerQuery);
while ($row = mysqli_fetch_array($countanswerresult)) {
    echo $row[0];
}


?> 

我希望能够自动对它们进行计数,而不是为每个问题/答案写一个sql查询。

2 个答案:

答案 0 :(得分:1)

  

例如,我想计算“ question_id”(问题)中“ answer_id”(答案的ID)1和2的回答次数

您可以按question_idanswer_id汇总结果,以找出每个问题为每个答案选择的时间,例如:

SELECT question_id, answer_id, COUNT(*) cnt
FROM survey_answers 
GOUP BY question_id, answer_id

如果yiou要过滤给定的问题,则可以添加WHERE子句:

SELECT question_id, answer_id, COUNT(*) cnt
FROM survey_answers 
WHERE question_id = ?
GOUP BY question_id, answer_id

答案 1 :(得分:1)

您要根据答案ID进行分组。

SELECT answer_id, COUNT(*) as count, question_id FROM survey_answers WHERE survey_id = $survey GROUP BY question_id , answer_id ORDER BY count DESC;

这将显示给定调查中所有问题的所有答案的数量。

这可能与以下内容重复

MySQL: Count the occurrences of DISTINCT values