1

我有两个表:问题(id_question,name_question,text_question)和选择(id_choice,text_choice,id_question)

我在 php 代码中的查询是:

$query =    ' SELECT q.name_question, q.text_question, c.text_choice'.
                        ' FROM question as q '.
                        ' LEFT JOIN choice as c ' .
                        ' ON q.id_question = c.id_question ' ;

当我检查结果时:

foreach ($db->loadObjectList() as $obj){

    echo $obj->name_question." ".$obj->text_question." ".$obj->text_choice."</br>";

}

我得到的是:

Q1 Q1_text C1
Q1 Q1_text C2
Q1 Q1_text C3

Q2 Q2_text C4
Q2 Q2_text C5

我想要的是:

Q1 Q1_text C1
           C2
           C3

Q2 Q2_text C4
           C5

那么有没有办法在 SQL 查询中做到这一点?以及如何以我想要的方式在 PHP 中显示查询结果?

谢谢你的帮助。

4

1 回答 1

0

这可以通过两种方式解决:

仅使用 SQL:

SQL小提琴:http ://www.sqlfiddle.com/#!2/19d46/14

  SELECT case
       when c.text_choice = (select min(text_choice) from choice c2 where c2.id = q.id) then name_question
       else ""
       end as name_question,

       case
       when c.text_choice = (select min(text_choice) from choice c2 where c2.id = q.id) then text_question
       else ""
       end as  text_question,
       c.text_choice 

FROM question as q LEFT JOIN choice as c  
ON q.id = c.id
order by q.id, c.text_choice;

结果:

Q1  Q1_text C1
C2
C3
Q2  Q2_text C4
C5
C6

也使用 PHP:

在初次查看时,这可以通过 PHP 轻松完成,并按 name_question 对结果进行排序。

$query =    ' SELECT q.name_question, q.text_question, c.text_choice'.
                        ' FROM question as q '.
                        ' LEFT JOIN choice as c ' .
                        ' ON q.id_question = c.id_question '  order by q.name_question;

显示结果时:

$current_nameQuestion = "";    
foreach ($db->loadObjectList() as $obj){

        if($current_nameQuestion==$obj->name_question)
        {
           echo "       ".$obj->text_choice."</br>";
        }
        else
        {
           echo $obj->name_question." ".$obj->text_question." ".$obj->text_choice."</br>";
           $current_nameQuestion = $obj->name_question;
        }       
    }

上面的 PHP 代码,只会在 2 列值name_question尚未输出时打印。

于 2013-05-23T12:09:03.487 回答