1

我正在尝试制作一个测验系统,但它输出:

Question1
Answer1
Question1
Answer2

等等..而不是

Question1
Answer1
Answer2
... and so on

我该如何解决?

代码:

$question = mysql_query("SELECT questions.*, answers.* FROM questions inner join answers on questions.id=answers.question_id");

while($row = mysql_fetch_assoc($question))
{
    echo $row['question'].'<br />' .$row['answer'].'<br />';            
}
4

2 回答 2

3

修复你的 WHILE 循环。它总是会打印问题和答案。快速修复看起来像这样:

$previousQuestion = null;
while($row = mysql_fetch_assoc($question))
{
    if($row['question'] !== $previousQuestion) {
        echo $row['question'].'<br />';
    }

    echo $row['answer'].'<br />';

    $previousQuestion = $row['question'];
}

可以通过其他方式简化语法,但这会起作用。基本上,由于问题与其答案之间存在一对多的关系,因此仅在问题与前一行的问题不同时才打印该问题。

于 2013-01-22T13:43:36.390 回答
0

如果你只想在 MySQL 中这样做,你可以这样做:

SELECT question AS 'Question And Its Answers'
FROM
(
  SELECT 0 AS Type, id, question FROM questions 
  UNION ALL
  SELECT 1, question_id, answer FROM answers 
) t
ORDER BY id, Type;

SQL 小提琴演示

这会给你:

| QUESTION AND ITS ANSWERS |
----------------------------
|                question1 |
|                      eee |
|                       dd |
|                      dsd |
|                question2 |
|                       df |
|                       fd |
|                question3 |
|                      ans |
|                       dd |
|                       ad |
于 2013-01-22T13:50:13.047 回答