douye2488 2014-09-09 08:43
浏览 31
已采纳

从mysql内连接显示值的最佳方法

I haven't been coding for a while, and i started a new project lately. In that project, i need to make a very simple inner join to associate values from 2 tables:

table questions:

 id  |  question  |  order
 1   |  how?      |  1
 2   |  what?     |  2
 3   |  when?     |  3

table answers:

 id_question  |  answer    |  order
 1            |  this way  |  1
 1            |  that way  |  2
 2            |  this      |  1
 2            |  that      |  2
 3            |  now       |  1
 3            |  later     |  2

How can I correctly get the questions and related answers, and display them, ordered by order?

I did this:

SELECT id, question, Q.order as qorder, id_question, answer, A.order as aorder FROM questions as Q INNER JOIN answers as A ON Q.id = A.id_question ORDER BY qorder

which result in this:

 id  |  question  |  qorder  | id_question  |  answer    |  aorder
 1   |  how?      |  1       | 1            |  this way  |  1
 1   |  how?      |  1       | 1            |  that way  |  2
 2   |  what?     |  2       | 2            |  this      |  1
 2   |  what?     |  2       | 2            |  that      |  2
 3   |  when?     |  3       | 3            |  now       |  1
 3   |  when?     |  3       | 3            |  later     |  2

DISPLAYING RESULTS:

$same_id = -1;
while ( $poll = $qa -> fetch() ) {
   if ($poll['id'] == $same_id ) { 
      echo '<li>'.$poll['answer'].'</li>';
   }
   else {
      if ( $poll['id'] == $same_id+1 ) { echo '</ul>'; }
      echo '<ul>'.$poll['question'];
      echo '<li>'.$poll['answer'].'</li>';
      $same_id = $poll['id'];
   }
   echo '</ul>';
}

which display:

<ul>How?
<li>this way</li>
<li>that way</li>
</ul>

<ul>What?
<li>this</li>
<li>that</li>
</ul>

<ul>When?
<li>now</li>
<li>later</li>
</ul>

it all works out, but it doesn't feel right.

First, I have the answers ordered by "luck", without specifying it in the request.

And then, the code feels too "complicated" for what it is.

I feel there is a better and cleaner way to do this kind of work.

  • 写回答

1条回答 默认 最新

  • doudouba4520 2014-09-09 09:00
    关注

    You can simply use the aorder to order explicitly:

    SELECT ...
    FROM ...
    INNER JOIN ...
    ORDER BY
        qorder ASC,
        aorder ASC
    

    Your code to display is alright. It could be improved by using PDOStatement::fetchAll() and foreach, but this is personal taste/preference.

    $polls = $qa->fetchAll();
    foreach($polls as $poll) {
        // output question and answers
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址