Skip to content
Advertisement

MySQL Generate conditional result based on join

I have 2 tables – department and employee.

Employee table: department_id is a foreign key from the department table (id column)

Department table:

I need help with a sql query that returns all rows in the employee table that matches the department_id in the department table with the following conditions.

  1. If the department id matches more than one non-unique employee_no (for eg, department_id 1 matches employee_no 34 & 35), then the join should get the dept_location which is ‘CA’ from the department table.

  2. If the department id matches unique employee_no even more than once (for eg, department_id 2 matches employee_no 36 twice), then the join from the department table is not applicable and the result should be ‘NA'(Not Applicable) for the dept_location

My result should look like the table below:

Advertisement

Answer

Here’s a query that will work in versions of MySQL prior to 8.0. It uses a derived table of counts of distinct employees per department to determine whether to display the department location or NA:

Output:

Demo on dbfiddle

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement