【发布时间】:2014-04-29 20:51:25
【问题描述】:
我的数据库中有两条表记录,如下所示:
第 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'];
【问题讨论】:
-
你能显示你的php代码吗?
-
Fiddle shows 2 replies 我想问题出在你的 php 代码中,你是如何获取结果的?
-
将table2作为LEFT JOIN的第一位