sql >> Database teknologi >  >> RDS >> Mysql

Eliminer duplikerede kolonner i MySQL venstre joinforespørgsel

Dette kan løses på to måder:

Bruger kun SQL:

SQL Fiddle: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;

Resultat:

Q1  Q1_text C1
C2
C3
Q2  Q2_text C4
C5
C6

Bruger også PHP:

Ved første visning kan dette nemt opnås via PHP og sortere dine resultater efter 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;

Når resultatet vises:

$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;
        }       
    }

Ovenstående PHP-kode vil kun udskrive de 2 kolonneværdier, når name_question er ikke allerede udsendt.




  1. Annoncering af ClusterControl 1.4.1 - ProxySQL-udgaven

  2. Hvordan opgraderer man PostgreSQL fra version 9.6 til version 10.1 uden at miste data?

  3. Brugerdefineret dato/klokkeslæt formatering i SQL Server

  4. Opdel kommasepareret streng og indsæt til en tabel (int)