[英]PHP: Left Join 2 table and print all records
我的數據庫中有兩個表記錄,如下所示:
表1帶有欄1:
topic_id name
21 my computer
表2的列如下:
reply_id topic_id message
1 21 blabla
2 21 blue
其中表2中的topic_id列是表1的外鍵
我想回顯表2中的所有答復以及表1中的主題名稱(#21)。因此,我像這樣進行查詢
$q="SELECT name, message
FROM table1
LEFT JOIN table2
ON table1.topic_id = table2.topic_id
";
但是,結果/輸出返回主題的名稱和僅一個答復,而不是預期的2(或全部)。 我錯過了什么?
我之所以使用LEFT JOIN,是因為某些主題仍在等待回復。 如果沒有任何答復,則在瀏覽器中仍會打印主題名稱。
我也嘗試添加
GROUP BY table1.topic_id
但還是沒有運氣!
你能幫我嗎? 謝謝
編輯:為了澄清這個問題,我添加了php代碼來獲取記錄,如下所示:
如您所知,名稱僅需打印一次。 所以,我這樣編碼:
$tid = FALSE;
if(isset($_GET['qid']) && filter_var($_GET['qid'], FILTER_VALIDATE_INT, array('min_range'=>1) ) ){
// create the shorthand of the question ID:
$tid = $_GET['tid'];
// run query ($q) as shown above
$r = mysqli_query($dbc, $q) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $q");
if (!(mysqli_num_rows($r) > 0) ){
$tid = FALSE; // valid topic id
}
}//isset($_GET['qid']
if ($tid) { //OK
$printtopic = FALSE; // flag variable to print topic once
while($content = mysqli_fetch_array($r, MYSQLI_ASSOC)){
if (!$printtopic) {
echo $content['name'];
$printtopic= TRUE;
}
}
} // end of $tid
// Print the messages if any:
echo $content['message'];
嘗試使用內部聯接
$q="SELECT name, message
FROM table1
INNER JOIN table2
ON table1.topic_id = table2.topic_id";
嘗試:
$q="SELECT table2.reply_id, table1.name, table2.message
FROM table2
LEFT JOIN table1
ON table1.topic_id = table2.topic_id
";
在解決了這個問題之后,我發現問題是我不得不將查詢更改為INNER JOIN並添加WHERE子句,如下所示:
WHERE table2.reply_id = {the given topic_id}
然后效果很好!
對不起,打擾大家了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.