所以我有一个 index.php 页面,它从数据库中的两个表中输出数据。第一个表 questions
包含我的 QuestionID 的一列,如下所示:
qid
----
1
2
3
名为 answers
的第二个表包含两列,一列用于我的 AnswersID,另一列链接到 questions
表上的我的 QuestionsID,它看起来像这样:
aid | aqid
----|-----
1 | 3
2 | 1
3 | 1
因此,在我的 index.php 页面上,我基本上想回显 questions
表中的每个 qid
行以及旁边的答案总数(answers
表中的 aid
行)对应于每个 QuestionID。
简单来说,我想要在我的index.php页面上实现的结果是这样的:
QuestionID: 1 / Answers: 2
QuestionID: 2 / Answers: 0
QuestionID: 3 / Answers: 1
但是根据我当前的代码,我很难实现这个结果。它不断回显每个表的错误行数。这是我得到的不需要的结果:
QuestionID: 1 / Answers: 3
QuestionID: 2 / Answers: 3
QuestionID: 3 / Answers: 3
那么我该如何解决这个问题以获得正确的结果呢?这是我当前的代码:
<?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 } ?>
感谢您的帮助。
最佳答案
group_concat()
返回一个连接字符串。您可能正在寻找count()
.
此外,count()
返回行计数。
似乎不需要 $row_cnt
或 foreach
。
这是一个例子:
$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
}
?>
关于php - 如何根据另一个表的ID获取表中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154370/