I have a table named DEPARTMENTS that has a column named EMPLOYEES which is a SET:
department | employees
----------------------
sales | 100,107
support | 120,121
And another table named EMPLOYEES:
employee | active
-----------------
100 | true
107 | false
120 | true
121 | true
I'm trying to void looping through the results and making another connection just to determine if the EMPLOYEE is ACTIVE. Basically, I need another column with the ACTIVE employees, the result something like:
department | employees | active
-------------------------------
sales | 100,107 | 100
I tried what I thought was an obvious:
SELECT departments.*, (SELECT GROUP_CONCAT(employee) FROM employees WHERE employee IN(departments.employees) AND active = true) AS active ...
Which failed and I don't understand why, because if I do this manually:
SELECT departments.*, (SELECT GROUP_CONCAT(employee) FROM employees WHERE employee IN(100,107) AND active = true) AS active ...
Which works.
Any advice appreciated:) Seems like a simple problem but for some reason escaping me..
Join the tables and aggregate with group_concat()
.
The function find_in_set()
can be used to link each emploee to each departmment.
Assuming that the data type of the column active
in employees
is Boolean
:
select d.department, d.employees,
group_concat(e.employee) active
from departments d left join employees e
on find_in_set(e.employee, d.employees) and e.active
group by d.department, d.employees
See the demo .
If active
's data type is varchar
change the ON
clause:
and e.active = 'true'
See the demo .
Results:
| department | employees | active |
| ---------- | --------- | ------- |
| sales | 100,107 | 100 |
| support | 120,121 | 120,121 |
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.