消除MySQL左连接查询中的重复列

时间:2013-05-23 12:03:40

标签: php mysql sql left-join

我有两张桌子: 问题(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中显示查询结果?

感谢您的帮助。

2 个答案:

答案 0 :(得分: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代码只会在name_question尚未输出时打印2列值。

答案 1 :(得分:-1)

尝试distinct

$query =    ' SELECT DISTINCT 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 ' ;