簡體   English   中英

嘗試通過使用另一個表中的id值將兩個表連接在一起

[英]Trying to connect two tables together by using id value from one table on the other

因此,我對sql還是很陌生,我正在嘗試弄清楚如何將兩個表連接在一起。

我有一個名為客戶的表和一個名為寵物的表,我想將寵物分配給特定的客戶。 我能夠為他們分配一個客戶值,但只能將其作為ID,當我在顯示我的數據的表中引用它時,我不知道如何獲取該ID並將其更改為客戶名稱。

例如,在我的客戶表中, customer id = 10; customerName = "John Smith"; customer id = 10; customerName = "John Smith";

然后我有寵物表petId = 16; petName = Alfredo; customerId = 10; petId = 16; petName = Alfredo; customerId = 10;

有沒有一種方法可以將peters表中的customerID = 10引用回到客戶表,以便我可以提取客戶名稱而不是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>";     
    ?>

是的,您好,您可以使用內部聯接來做到這一點:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM