MySQL查询-同一个相关表中多个字段的内部连接

gab6jxml  于 2023-02-03  发布在  Mysql
关注(0)|答案(2)|浏览(130)

表“商店”包含有关商店及其主管和助理出纳员的信息。主管出纳员和助理出纳员是从表“雇员”中选择的。
商店

StoreID | StoreName | LeadCashierID | AssistantCashierID
001     | Store1    |      1        |         2
002     | Store2    |      1        |         3
003     | Store3    |      2        |         3

雇员

EmployeeID | EmployeeName
1          | John
2          | Paul
3          | Steve

我需要设置一个查询,显示StoreID,主管出纳员的姓名和助理出纳员的姓名。我会建立类似的查询,但我不知道如何在一个查询中回显主管出纳员的姓名和助理出纳员的姓名。

SELECT StoreID, StoreName, EmployeeName FROM Stores
JOIN Employees ON Employees.EmployeeID = Stores.LeadCashierID 
JOIN Employees ON Employees.EmployeeID = Stores.AssistantCashierID
dwbf0jvd

dwbf0jvd1#

您只需要表别名:

SELECT s.StoreID, s.StoreName, le.EmployeeName as LeadName,
       ae.EmployeeName as AssistantName
FROM s.Stores JOIN
     Employees le
     ON le.EmployeeID = s.LeadCashierID JOIN
     Employees ae
     ON ae.EmployeeID = s.AssistentCashierID;

提示:使用表别名的表缩写。它们使查询更容易理解。

pxq42qpu

pxq42qpu2#

可以使用表别名。

$sql = "SELECT StoreID, StoreName, leadCashier.EmployeeName as 
LeadCashier, 
assCashier.EmployeeName as AssistantCashier 
FROM Stores
JOIN Employees leadCashier ON leadCashier.EmployeeID = 
Stores.LeadCashierID 
JOIN Employees assCashier ON assCashier.EmployeeID = 
Stores.AssistantCashierID";
$result = $db->query($sql);

echo "<table>";
echo "<tr><th>Store ID</th><th>Store Name</th><th>Lead Cashier</th> 
<th>Assistant Cashier</th></tr>";

if ($result->num_rows > 0) {
// output data of each row
    while($row = $result->fetch_assoc()) {
    echo "<tr>";
    echo "<td>" . $row["StoreID"]. "</td>";
    echo "<td>" . $row["StoreName"]. "</td>";
    echo "<td>" . $row["LeadCashier"]. "</td>";
    echo "<td>" . $row["AssistantCashier"]. "</td>";
    echo "</tr>";
    }
} else {
    echo "0 results";
}
echo "</table>";

相关问题