php - 尝试通过使用另一个表中的 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>";
?>
解决方案
是的,你好,你绝对可以通过内部连接来做到这一点:
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
}
推荐阅读
- android - 如何跳过名称中包含“单词 A”的所有任务?
- r - ifelse在R中有两个条件数字和分类
- python - 有没有办法在 Python 中运行 for 循环而不必将列表传递给它?
- lucene - 如何对 Lucene 查询的结果进行分组,按组计算命中并突出显示某些选定组中的文档?
- typescript - transpileOnly 时 ts-loader 时间超慢:假?
- react-native - 将 react-native 中的多个 html-tags 替换为 Text
- javascript - 分配中的左侧无效,但我正在尝试分配一个变量
- c++ - msvc++ 和 clang 怎么知道这个结构的大小,甚至不需要前向声明?
- pandas - how remove spaces from a dataframe separated by ,
- android - Xamarin Android Webview:getUserMedia 无法打开相机