Senior
CREATE TABLE staff ( id TEXT name TEXT head_id TEXT ); id | name | head_id -------------------- 1 | Ivan | NULL 2 | Petr | 1 3 | Alice | 1 4 | Max | 2 5 | Alex | 2 6 | Elena | 4 7 | Bob | NULL Expected output: employee_name | manager_name --------------------------- Ivan | NULL Petr | Ivan Alice | Ivan Max | Petr Alex | Petr Elena | Max Bob | NULL SELECT e.name AS employee_name, m.name AS manager_name FROM staff e LEFT JOIN staff m ON e.head_id = m.id
sobes.tech AI
Answer from AI
In the provided SQL query example, it correctly implements the output of a list of employees and their managers from a single staff table using a self JOIN.
The staff table contains fields id, name, and head_id, where head_id is a reference to the id of the employee's manager.
Query:
SELECT e.name AS employee_name, m.name AS manager_name
FROM staff e
LEFT JOIN staff m ON e.head_id = m.id
eis an alias for employees.mis an alias for their managers.- LEFT JOIN ensures that even employees without a manager (for example, Ivan and Bob) will have a row with
manager_name= NULL.
Thus, the query outputs the names of employees and their managers if they exist, which matches the expected result.