php - 如果来自两个不同表的 ID 相等,则显示来自另一个表的名称

标签 php mysql sql

我正在为我的小管理面板编写代码,由于我不是那么高级的编码员,我在使用两个不同的表获取名称时遇到了一些麻烦。

到目前为止,这是我的代码:

<?php

session_start();
if(!session_is_registered(myusername)){
    header("location:main_login.php");
}

include 'db_connect.php';

$sql = "SELECT * FROM $tbl_name WHERE is_dead='0'";
$result=mysql_query($sql);
?>

<title>Title</title>
<center><img src="header.png"></center>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<? include 'menu.php';?>
</tr>

<tr>
<td align="center"><strong>ID</strong></td>
<td align="center"><strong>Unique ID</strong></td>
<td align="center"><strong>Model</strong></td>
<td align="center"><strong>Last Online</strong></td>
<td align="center"><strong>Options</strong></td>
</tr>

<?php
while($rows=mysql_fetch_array($result)){
?>

<tr>
<td><? echo $rows['id']; ?></td>
<td><? if ($rows['unique_id'] == 7815684) { echo '<font color="blue"><b><u>7815684</u></b></font>'; }
elseif ($rows['unique_id'] == 2312964) { echo '<font color="blue"><b><u>2312964</u></b></font>'; }
else { echo $rows['unique_id']; } ?></td>
<td><? echo $rows['model']; ?></td>
<td align='center'><font color="green"><b><? echo $rows['last_updated']; ?></b></font></td>
<td align="center"><a href="update.php?id=<? echo $rows['id']; ?>">update</a>
</tr>
<?php
}
?>

</table>
</td>
</tr>
</table>

所以我要做的是获取用户名,使用两个表 $tbl_name$prtalbe 使用它们的 unique_id。因此,如果来自 $tbl_name 的 unique_id 等于来自 $prtable 的 unique_id,我想显示来自 $prtalbe 的用户名。

我一直在尝试另一个 sql 查询:

$sql = "SELECT * FROM $tbl_name, $prtable WHERE $tbl_name.unique_id = $prtable.unique_id;
$result=mysql_query($sql);

然后执行 while 循环使其工作

while($rows=mysql_fetch_array($result)){
   $rows['name'];
}

它确实有效,但它不想将它直接放入我的代码中,因为 ID 来自 $prtable$tbl_name 是不同的。

最佳答案

试试这个:

$sql = "SELECT $prtable.username FROM $tbl_name INNER JOIN $prtable ON ($tbl_name.unique_id = $prtable.unique_id)"; 

当您调用 INNER JOIN 时,您将从每个表中获取所有行,并在给定 ON 条件的情况下组合它们。有关详细信息,请参阅:http://www.w3schools.com/sql/sql_join_inner.asp

关于php - 如果来自两个不同表的 ID 相等,则显示来自另一个表的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18109211/

相关文章:

mysql - 仅当它们之间的差异超过 15 分钟时如何获取 2 条记录

sql - 避免 MySQL 中有问题的嵌套查询

java - 执行和sql字符串

php - 使用套接字传递按钮单击事件

php - Yii2-SQLSTATE[42000] : Syntax error or access violation: 1064 on insert batch

php - Node + now.js + 模型- View -控制-模式

php - 2 个模块的 1 个 sql 请求。乔姆拉

php - SQL : Command Create Virtual Row If Not Exist

php - 我想使用 Ajax 将 id 从 View 传递到 Codeigniter 中的 Controller 并更新数据库中的下拉选择

android - 如何使用数据库数据分发 Android 应用程序?