我在数据库中有两个表。表questions
,有两列,ID
和question
。表二 answers
有两列 question_ID
和 answer
。在表 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/