首页 > 解决方案 > 尝试通过使用另一个表中的 id 值将两个表连接在一起

问题描述

所以我对 sql 很陌生,我正在尝试弄清楚如何将两个表连接在一起。

我有一个名为 customers 的表和一个名为 pets 的表,我想将宠物分配给特定的客户。我可以为他们分配一个客户价值,但只能作为 id,当我在显示我的数据的表中引用它时,我无法弄清楚如何获取该 id 并将其更改为客户名称。

所以例如在我的客户表中 customer id = 10; customerName = "John Smith";

然后我有宠物桌 petId = 16; petName = Alfredo; customerId = 10;

有没有办法将 customerID = 10 从 pets 表引用回客户表,以便我可以提取客户的姓名而不是 id?

这是我显示列出宠物查询的表的代码,where $row['customer']我想显示客户姓名,而不是 id。

谢谢

        <?php 
      $sql = "SELECT * from pets ORDER BY petName ASC";

      echo "<table class='tableInfo' cellpadding='8'>";
      echo "<tr><th>Pet Name</th><th>Owner</th><th colspan='2'>Action</th></tr>";
      $result = mysqli_query($con, $sql);

      while($row = mysqli_fetch_array($result)){    
          echo "<tr>";    
          echo '<td>' . $row['petName'] .'</td>';    
          echo '<td>' . $row['customerId'] .'</td>'; 
          echo '<td><a href="editPets.php?id=' . $row['id'] . '">Edit</a></td>';    
          echo '<td><a href="deletePets.php?id=' . $row['id'] . '">Delete</a></td>';    
          echo "</tr>";    
    }
        echo "</table>";     
    ?>

标签: phpmysqlsql

解决方案


是的,你好,你绝对可以通过内部连接来做到这一点:

select * from pets
join customers on pets.customerId = customers.customerId
order by petName

听起来查询可能正在返回错误。也许打印错误:

$res = mysqli_query($con, $sql) or die ('Query failed: ' . mysqli_error($con));

while ($row = mysqli_fetch_assoc($res)) {
    // Do something with row
}

推荐阅读