![](/img/trans.png)
[英]How do I get rows to correspond to other rows based on a parent_id , all from the same table
[英]How to get number of rows from table based on ID from another table
所以我有一个index.php页面,它从数据库的两个表中吐出数据。 在第一个表中, questions
包含我的QuestionID的一列,如下所示:
qid
----
1
2
3
第二个表称为answers
包含两列,一列用于我的AnswersID,另一列链接到questions
表上的我的QuestionsID,看起来像这样:
aid | aqid
----|-----
1 | 3
2 | 1
3 | 1
因此,在我的index.php页面上,我基本上想在questions
表中回显每个qid
行,并在其旁边回显与每个QuestionID相对应的answers
总数 (从answers
表开始的aid
行)。 简而言之,我想要在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
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.