[英]Print data from two different tables with a shared field (mysql and php)
I'm trying to bring data from two different tables where there is a shared field: in table1, I have many fields and one of them is the employee Position which is a number. 我正在尝试从两个不同的表中提供数据,其中有一个共享字段:在table1中,我有许多字段,其中一个是员工Position ,这是一个数字。 in table2 I have two fields: EmpPos (which is equal to Position in table1) and PosName .
在table2中我有两个字段: EmpPos (等于table1中的Position )和PosName 。 Now, I want to print all employees' info from table1 but instead of printing Position (which is a number), I want to print its associated PosName from table2.
现在,我想从table1打印所有员工的信息,但不是打印Position (这是一个数字),我想从table2打印其关联的PosName 。 My following query is not working!
我的以下查询无效!
$sql ="SELECT * FROM table1, table2 WHERE table1.Position=table2.EmpPos";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
<tr>
<th>Name</th>
<th>Email</th>
<th>Position Name</th>
<th>phoneExt</th>
</tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" .$row['table1.FirstName'] ." " .$row['table1.LastName'] ."</td>";
echo "<td>" .$row['table1.Email'] ."</td>";
echo "<td>" .$row['table2.PosName'] ."</td>";
echo "<td>" .$row['table1.phoneExt'] ."</td>";
echo"</tr>";
}
Thanks in advance 提前致谢
The issue is you didn't define any relationship between the tables. 问题是您没有定义表之间的任何关系。 So you should be using INNER or LEFT JOIN for this:
所以你应该使用INNER或LEFT JOIN:
SELECT * FROM Table1 m INNER JOIN
Table2 k ON k.EmpPos = m.Position
Or the following should do: 或者以下应该做:
SELECT * FROM Table1 m LEFT JOIN
Table2 k ON k.EmpPos = m.Position
As you have a foreign key (Shared field), then it's easy and obvious to use joins. 由于您有一个外键(共享字段),因此使用连接很容易也很明显。
使用内部联接
SELECT * FROM table1 tab1 INNER JOIN table2 tab2 ON tab1.position = tab2.EmpPos
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.