【问题标题】:Select all records from table 1 then select all records from table 2 matching table 1 primary key从表 1 中选择所有记录,然后从表 2 中选择与表 1 主键匹配的所有记录
【发布时间】:2020-03-09 02:32:15
【问题描述】:

我有两张桌子 第一个具有主键 c_id 的表。 第二个表有自己的主键和外键c_id(表2可以有多个与表1相关的条目)

我正在尝试查询第一个表中的所有记录,但也查找第二个表中与主键匹配的所有记录,并将其列中的一列回显到查询中的列。

这是我的代码 注意:对连接表不熟悉,因此以下代码只是回显表 1 中的记录。

 <?php
 include_once('connected.php');
 if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
  } 

 $sql = "SELECT * FROM files ORDER BY c_id Desc";

   if ($result=mysqli_query($conn,$sql))
 {
 // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
 printf("Total = %d \n",$rowcount);
 // Free result set
  mysqli_free_result($result);
  }

  $result = $conn->query($sql);
   if ($result->num_rows > 0) {
    //output data of each row
     while($row = $result->fetch_assoc()) {
      echo "<tr> 

                    <td> <b>". $row["c_no"]." </b>
                    <td> <b>". $row["c_applicants"]. " </b> //this rows should echo all records from 2nd table
                    <td> <b>". $row["c_details"]. " </b>
                    <td> <b>". $row["c_for"]. " </b>
                    <td> <b>". $row["c_person"]. " </b>
                    <td> <b>". $row["c_country"]. "</b>
                    <td> <b>". $row["c_rdate"]. " </b>
                    <td> <b>". $row["c_galdate"]. "</b>
                    <td> "."<a href=viewfile.php?id=". $row['c_id'] .">Expand</a>". "<br>";

     }
  } else {
  echo " results";
 }
  $conn->close();
  ?>  

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    您应该能够从表 1 -> 表 2 编写连接查询。

    这是beginners 的一个很好的资源

    作为一个起点,这里有一个查询,您可能需要对其进行调整,但可以让您找到正确的方向。

    select columns, you, actually, want from table1 as t1
    join table2 as t2
    on t1.id = t2.other_id
    order by t1.id desc
    

    【讨论】:

    • $sql = "select * from files inner join applications on files.c_id=applicants.c_id";我能够加入,但我希望申请人的所有记录都回显到该行的一个列。 (连接或某种形式。)他们将是一个文件的多个申请人,所以我只想在这一行的列上显示所有申请人的姓名。我希望我说得通。感谢您的帮助,我将继续阅读您发送的链接。
    • 我认为您在谈论“一对多”连接。看看这个问题here
    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多