Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noblemfd's avatar

Self Referencing make left join not to give correct result

I have three tables in mysql database: hr_employees, appraisal_goals and hr_departments

SELECT DISTINCT e.employee_code, concat(e.first_name,' ',e.last_name) Fullname, e.email,
CASE
    WHEN a.line_manager_mid_year_approved = 0 THEN "DRAFT"
    WHEN a.line_manager_mid_year_approved = 1 THEN "AWAITING APPROVAL"
    WHEN a.line_manager_mid_year_approved = 2 THEN "NOT APPROVED"
    WHEN a.line_manager_mid_year_approved = 3 THEN "APPROVED"
ELSE "NOT STARTED"
END AS line_manager_mid_year_approved,d.dept_name,
e.grade_level_name, concat(em.first_name,' ',em.last_name) as manager
FROM hr_employees e
LEFT JOIN appraisal_goals a ON a.employee_id = e.id
INNER JOIN hr_departments d
ON e.department_id = d.id
INNER JOIN hr_employees em
ON em.employee_code = e.line_manager_id
WHERE e.company_id = 1 
AND e.hr_status = 0 
AND e.validation_status = 'VALID'
AND e.employee_type_code NOT IN (4,5);
  1. using left join, All the employees are to be selected whether they have data in hr_departments and appraisal_goals or not.

  2. Each employee have a line manager

Initially, without the self referencing (where no line manager data selected) everything was working perfectly. In order to get the manager full name, I did self referencing where em.employee_code = e.line_manager_id. As soon as I did this, the query only select the employees that have data in the appraisal_goals.

How do I correct this, so that the left join will still be working?

Thanks

0 likes
7 replies
noblemfd's avatar

@jlrdw - I applied the same thing, but I don't know why the self join is not making the left join to give the right result

jlrdw's avatar

I know one thing about join it can be tricky sometimes.

Usually when I do joins, grouping, etc, I use a visual query builder like (SQLeo) to make sure I get the correct results, then convert to a PDO / SQL query.

If you do this stuff often, get a good paid visual query designer.

jlrdw's avatar

See if DISTINCT is throwing you off. I know these types of queries can take time to figure out. Maybe you need a grouping of line_manager.

So is e.line_manager_id from parent and in employee you probably need a foreign key relating that employee to the line manager. But not knowing your data I'm just guessing.

And could the data you need be done in two queries instead of one?

em.employee_code = e.line_manager_id

Is that part correct, the em.employee_code references the e.line_manager_id.

noblemfd's avatar

@jlrdw - I want the data I need to be in one query so that I can just render it in the blade blade from the controller

jlrdw's avatar

Try also selecting e.line_manager_id also. All items used need selected also.

Edit: is em.employee_code correct, above you have e.employee_code, I just noticed this.

Please or to participate in this conversation.