php - 如何一次从多个表中获取数据?

标签 php mysql

我在数据库中有两个表。表questions,有两列,IDquestion。表二 answers 有两列 question_IDanswer。在表 answers 中,一个问题有多个答案。所以有重复的question_ID。我如何显示表 questions 中的所有问题以及表 answers 中问题下方的所有相关答案?喜欢:

太阳有多远?

太阳距离我们有 1800 万英里。
太阳在 9300 万英里之外。
太阳在 2 英里之外。

太阳有多大?

大。
小。
中等。

等...

抱歉,如果这个问题看起来有点含糊,但这是我能解释的最好方式。 提前致谢。

最佳答案

您将执行连接两个表的选择查询,按问题 ID 排序。

SELECT q.ID as question_id, q.question, a.ID as answer_id, a.answer
FROM questions q
LEFT JOIN answers a ON a.question_ID = q.ID
ORDER BY q.ID, a.ID

这将为您提供如下结果集:

question_id   question                 answer_id   answer
1             What color is the sky?   100         Blue
1             What color is the sky?   101         Red
2             How old is dirt          102         Very Old
2             How old is dirt          103         Kinda Old

等等

当您遍历此结果集时,您需要跟踪最后一个问题是什么,以便当您转到第三个结果(问题 2)时,您知道要显示下一个问题。

例如

$PreviousQid = null;
foreach ($QueryResult as $QueryRow)
{
   if ($PreviousQid === null || $PreviousQid != $QueryRow['question_id'])
   {
       echo "<b>" . $QueryRow['question'] . "</b><br/>\n";
   }

   echo $QueryRow['answer'] . "</br>\n";

   $PreviousQid = $QueryRow['question_id'];
}

关于php - 如何一次从多个表中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4160789/

相关文章:

Php 不能使用对象 stdClass 作为数组

php - 接受/拒绝提交按钮与 php 循环

php - 基于日期的年份报表查询

php - 来自一个表单的多个 mysql 插入

php - 将表单数据插入 MySQL?

PHP MYSQL BLOB 导出为 csv 格式

php - 限制 CPU 负载或设置进程优先级

MySQL,一次查询更新多个表

php - 在 php $query 中选择 mysql 数据库的表

php - MySQL 选择另一个表中缺少的条目