假设我有三个表:
地点 - 一个商店可以属于多个地点,一个地点可以有多个商店
+-------------+----------+ | LOCATION_ID | STORE_ID | +-------------+----------+
STORES - only one row per store, every store has only one manager ID
+----------+------------+ | STORE_ID | MANAGER_ID | +----------+------------+
EMPLOYEES - a manager can have multiple employees, and employees can belong to more than one manager
+-------------+-------------+ | MANAGER_ID | EMPLOYEE_ID | +-------------+-------------+
And for a given location (e.g. LOCATION_ID = 999), I want to get all the employees managed at stores at that location.
This gets me the list of managers that belong to stores in that location:
SELECT s.MANAGER_ID FROM LOCATIONS l
INNER JOIN STORES s
ON s.STORE_ID = l.STORE_ID
WHERE l.LOCATION_ID = 999;
我真正想要的是链接到查询吐出的经理的所有不同的 EMPLOYEE_ID。
我可以在同一查询中添加哪些附加联接来获得该结果?
最佳答案
SELECT DISTINCT E.EMPLOYEE_ID
FROM LOCATIONS L
INNER JOIN STORES S ON S.STORE_ID = L.STORE_ID
INNER JOIN EMPLOYEES E ON S.MANAGER_ID = E.MANAGER_ID
WHERE L.LOCATION_ID = 999;
关于MySQL 连接返回从另一个表链接的不同 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4271170/