简体   繁体   中英

MySQL join to return distinct IDs linked from another table

Let's say I have three tables:

LOCATIONS - a store can belong to multiple locations and a location can have multiple stores

+-------------+----------+
| 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 (eg 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;

What I actually want is ALL the distinct EMPLOYEE_IDs that are linked to the managers that query spits out.

What additional join can I add in the same query to get that?

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; 

Adding INNER JOIN Employees e ON s.MANAGER_ID = e.MANAGER_ID should get you the employees.

But I notice you're asking for how to select all the distinct employee IDs. Change your SELECT clause to SELECT DISTINCT e.EMPLOYEE_ID , rather than returning the store managers' IDs.

RedFilter's answer spells it out nicely. :)

SELECT e.EMPLOYEE_ID ... INNER JOIN EMPLOYEES e ON e.MANAGER_ID = s.MANAGER_ID ...

您可以在员工ID之前添加DISTINCT关键字,但是,如果数据已正确规范化,则没有必要。

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