I have a Sotrudniki table - there are employee ID , FIO (employees), and ID_MANAGER (ID managers). Managers are employees.

For example, employee IDs are 100, 101, 102, 103 and their employee manager is ID 100. I need to withdraw FIO employees and their managers by name (FIO).

Closed due to the fact that the issue is too general for the participants Kirill Stoianov , Kromster , Denis , HamSter , aleksandr barakin Sep 30 '16 at 10:25 .

Please correct the question so that it describes the specific problem with sufficient detail to determine the appropriate answer. Do not ask a few questions at once. See “How to ask a good question?” For clarification. If the question can be reformulated according to the rules set out in the certificate , edit it .

    3 answers 3

    It is better to use LEFT JOIN , if you want to withdraw and employees without managers. Otherwise, replace LEFT JOIN with INNER JOIN

     SELECT s.fio as sotrudnik_id, m.fio as manager_id FROM Sotrudniki s LEFT JOIN Sotrudniki m ON s.id_manager = m.id ORDER BY s.fio; 
    • I do not have the same name managers. I only have full names of employees, and managers only have ID_MANAGER. Here I need to withdraw employees with their managers. Some employees are managers. - user221601
    • @ user221601 Have you tried the request? he will give exactly what you asked for the name of the employee and the name of his manager. - Mike
    • @ user221601 That's right. In this query, the table is combined with itself, the record of its manager is added to the employee record. But if there are employees in the table who do not have a manager ( ID_MANAGER empty), then they will be ID_MANAGER in the variant with LEFT JOIN they will not be INNER JOIN in the variant with INNER JOIN . Quite often, this distinction is important, so I decided to write about it just in case. You can read more about JOIN in specialized literature or documentation. - Andrey1990
     SELECT s1.fio, s2.fio FROM Sotrudniki s1 JOIN Sotrudniki s2 ON s1.id_manager = s2.id; 

      Try this query:

       SELECT s.fio AS sotrudnik_fio, m.fio AS manager_fio FROM sotrudnik s LEFT JOIN sotrudnik m ON s.id_manager = m.id ORDER BY m.id 

      An example on sqlfiddle .

      Your question resembles this one , in fact, a duplicate.