[英]best way to display value from mysql inner join
我已經有一段時間沒有編碼了,最近我開始了一個新項目。 在那個項目中,我需要做一個非常簡單的內部聯接來關聯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>
一切正常,但是感覺不對。
首先 ,我有按“運氣”排序的答案,而未在請求中指定。
然后 ,代碼本身就顯得“過於復雜”。
我覺得有一種更好更清潔的方式來進行這種工作。
您可以簡單地使用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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.