简体   繁体   中英

MySQL Query - inner join on multiple fields from the same relating table

Tables Stores has information about stores and its Lead and Assistant cashiers. LeadCashier and AssistantCashier are selected from table Employees.

Stores

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

Employees

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

I need to set up a query that would display StoreID, LeadCashier's Name and AssistantCashier's name. I would build query similar to this, however I can't figure out how to echo the LeadCashier's name and AssistantCashier's name in a single query.

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

You simply need table aliases:

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;

Tip: Use table abbreviations for the table aliases. They make the query easier to follow.

You can use table aliases.

$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>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM