I have a mysql table with the following structure:
Assign | Pri | Sec | Ter | Qua |
---|---|---|---|---|
21 | Tom | Mark | Sally | Tammy |
60 | Sally | Ace | Tom | Mark |
170 | Mark | Sally | Ace | Tammy |
220 | Ace | Tammy | Tom | Sally |
17 | Tammy | Sally | Mark | Ace |
439 | Sally | Tom | Tammy | Mark |
I want to display the employees assignments based on primary assignments and if there are any absences, based on their status as secondary, tertiary or quaternary. So for Sally, her assignments are 60 and 439 every day. But if Tom and Mark are absent, her assignments would be 60, 439, 21 and 170. What I have only pulls assignments based on if Sally is secondary, tertiary or quaternary but doesn’t take into account if, when Sally is tertiary or quaternary, if the person in front of them (secondary or tertiary) is in the office and has taken that assignment. So with my query, she would get assignments, 60, 439, 21, 170, 220 and 17.
This is what I have so far that doesn’t have the logic I need.
SELECT
Assign
FROM
assign_table
WHERE
Pri = 'Tom'
AND
sec = 'Sally'
OR
pri = 'Tom'
AND
ter = 'Sally'
OR
pri = 'Tom'
AND qua = 'Sally'
OR
pri = 'Sally'
ORDER BY
Assign;
I should mention I have another table with employee names and an absent column that contains 0 or 1 if they are in the office or absent that particular day (employee_credentials).
Any help is appreciated.
2
Answers
Join the
assign_table
andemployee_credentials
and use the conditional logic to determine the assignments based on absence of status of other employees. May be this code would workwe can use UNION to combine.
Thanks
If you are using MySQL ≥ 8.0.14, you can use
CROSS JOIN LATERAL
to unpivot the data inassign_table
. See Lateral Derived Tables.Assuming your
employee_credentials
table looks like this:You can use the following query to unpivot
assign_table
and join toemployee_credentials
to determine whether the employee is absent, or not. You then use ROW_NUMBER() to assign a new priority for each assignment.Output:
Your
assign_table
holds an ordered many-to-many relationship between employees and tasks/assignments, so a better structure might look like:employees
assignments_employees
employee_absence
With this structure the query becomes:
Output:
The CTEs in both of these queries can be made more efficient by restricting assignments to those to which Sally is already assigned.
Here’s a db<>fiddle to play around with.