[英]How to get number of rows from table based on ID from another table
So I have an index.php page that spits out data from two tables on my database. 所以我有一个index.php页面,它从数据库的两个表中吐出数据。 The first table,
questions
contains one column for my QuestionID and looks like this: 在第一个表中,
questions
包含我的QuestionID的一列,如下所示:
qid
----
1
2
3
The second table called answers
contains two columns, one for my AnswersID and the other which links to my QuestionsID on the questions
table, and it looks like this: 第二个表称为
answers
包含两列,一列用于我的AnswersID,另一列链接到questions
表上的我的QuestionsID,看起来像这样:
aid | aqid
----|-----
1 | 3
2 | 1
3 | 1
So on my index.php page, I basically want to echo out every qid
row from the questions
table and beside it the total number of answers ( aid
rows from the answers
table) corresponding to each QuestionID . 因此,在我的index.php页面上,我基本上想在
questions
表中回显每个qid
行,并在其旁边回显与每个QuestionID相对应的answers
总数 (从answers
表开始的aid
行)。 To put simply, the result I want achieved on my index.php page is this: 简而言之,我想要在index.php页面上实现的结果是:
QuestionID: 1 / Answers: 2
QuestionID: 2 / Answers: 0
QuestionID: 3 / Answers: 1
But based on my current code I am having trouble achieving this result. 但是根据我当前的代码,我很难达到这个结果。 It keeps echoing out the wrong number of rows for each table.
它不断回显每个表的错误行数。 This is the unwanted result I am getting:
这是我得到的不必要的结果:
QuestionID: 1 / Answers: 3
QuestionID: 2 / Answers: 3
QuestionID: 3 / Answers: 3
So how would I fix this to achieve the correct result? 那么,如何解决此问题以获得正确的结果? This is my current code:
这是我当前的代码:
<?php
$sql = "
SELECT questions.*, GROUP_CONCAT(answers.aqid) AS aqid
FROM questions
LEFT JOIN answers
ON questions.qid=answers.aqid
GROUP BY questions.qid
";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$qid = $row["qid"];
$aqid = $row["aqid"];
$row_cnt = $result->num_rows;
?>
<div>
QuestionID: <?php echo $qid; ?>
<?php foreach($answers as $answer): ?>
Answers: <?php echo $row_cnt; ?>
<?php endforeach; ?>
</div>
<?php } ?>
Thank you for your help. 谢谢您的帮助。
group_concat()
returns a concatenated string. group_concat()
返回一个串联的字符串。 You might be looking for count()
. 您可能正在寻找
count()
。
Also, count()
returns a row count. 同样,
count()
返回行数。
There doesn't seem to be a need for $row_cnt
or the foreach
. 似乎不需要
$row_cnt
或foreach
。
Here's an example: 这是一个例子:
$sql = "
SELECT
q.`qid`,
COUNT(a.`aqid`) AS `answerCount`
FROM `questions` q
LEFT JOIN `answers` a
ON a.`aqid` = q.`qid`
GROUP BY q.`qid`
";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
?>
<div>
QuestionID: <?php echo $row["qid"]; ?>
Answers: <?php echo $row["answerCount"]; ?>
<div>
<?php
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.