我試圖從兩個不同的表中共享字段的數據: 在table1中,我有很多字段,其中之一是員工職位這是一個數字。 in table2我有兩個字段:EmpPos(它等於位置在表1中)和PosName。 現在,我想打印來自table1的所有員工信息,但不是打印職位(這是一個數字),我想打印其關聯的PosName from table2。 我的下列查詢不起作用!使用共享字段(mysql和php)從兩個不同的表中打印數據
$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>";
}
在此先感謝
你的意思,我要在數據庫中定義的外鍵?因爲我想你的代碼,並給出了這個錯誤:(未定義指數:table1.FirstName)和相同的所有字段 – user2148116
我可以看到,已經有一個外鍵定義。在這兩個表中,您都有一個字段positionId。根據你的情況改變表名和列。 –
它與左連接,謝謝 – user2148116