【问题标题】:PHP: Left Join 2 table and print all recordsPHP:左连接 2 表并打印所有记录
【发布时间】: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的第一位

标签: php mysql


【解决方案1】:

用内部连接试试这个

$q="SELECT name, message
FROM table1
INNER JOIN table2
ON table1.topic_id = table2.topic_id";

【讨论】:

  • 根据提供的样本数据集,使用inner或left都没关系,你访问过fiddle with left join
  • 是的。我认为问题出在我的 php 代码中以获取记录。
  • 我只是在问题中添加了 php 代码来澄清它。你能帮忙吗?
【解决方案2】:

试试:

$q="SELECT table2.reply_id, table1.name, table2.message
FROM table2
LEFT JOIN table1
ON table1.topic_id = table2.topic_id
";

【讨论】:

    【解决方案3】:

    在解决了这个问题后,我发现问题是我必须将查询更改为 INNER JOIN 并添加 WHERE 子句,如下所示:

    WHERE table2.reply_id = {the given topic_id}
    

    那就好办了!

    很抱歉打扰大家!

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 2018-08-30
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多