我还没有编码一段时间,最近我开始了一个新项目。 在该项目中,我需要创建一个非常简单的内部联接来关联来自2个表的值:
表格问题:
id | question | order
1 | how? | 1
2 | what? | 2
3 | when? | 3
表答案:
id_question | answer | order
1 | this way | 1
1 | that way | 2
2 | this | 1
2 | that | 2
3 | now | 1
3 | later | 2
如何正确获取问题及相关答案,并按顺序排列?
我这样做了:
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
结果如下:
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
显示结果:
$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>';
}
显示:
<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>
一切顺利,但感觉不对。
首先,我的答案是&#34;运气&#34;,而未在请求中指明。
然后,代码感觉太复杂&#34;它是什么。
我觉得有更好,更清洁的方式来做这种工作。
答案 0 :(得分:0)
您只需使用aorder
明确订购:
SELECT ...
FROM ...
INNER JOIN ...
ORDER BY
qorder ASC,
aorder ASC
您要显示的代码没问题。可以使用PDOStatement::fetchAll()
和foreach
进行改进,但这是个人品味/偏好。
$polls = $qa->fetchAll();
foreach($polls as $poll) {
// output question and answers
}