I'm using the employees test database, available here: https://github.com/datacharmer/test_db

I'm trying to get names of employees who have the same last name as their manager. I wish to make the query below faster.
SELECT concat(first_name,' ',last_name)
FROM
((employees JOIN dept_emp ON employees.emp_no=dept_emp.emp_no)
JOIN dept_manager ON dept_emp.dept_no=dept_manager.dept_no)
WHERE employees.last_name=
(SELECT last_name FROM employees WHERE employees.emp_no=dept_manager.emp_no);
As you can see, there's a select in the where clause that searches the entire table. I assume that means for each row of the joined table, it will the entire employees table.
I tried to solve it by creating a smaller table before joining, but it's even 4x slower.
SELECT concat(B.first_name,' ',B.last_name)
FROM
(SELECT employees.emp_no, employees.last_name, dept_no
FROM employees JOIN dept_manager ON employees.emp_no=dept_manager.emp_no) AS A
JOIN
(SELECT employees.first_name, employees.emp_no, last_name, dept_no
FROM employees JOIN dept_emp ON employees.emp_no=dept_emp.emp_no) AS B
ON (A.dept_no=B.dept_no AND A.last_name=B.last_name);
WITH.dept_managerand adddept_emp_noin tabledepartments. If you are trying to keep a history of who worked for a dept when and track their movements?to_datesome time in the future? Or maybeNULLmeans "current"? If not, it is hard to optimize the query without knowing.