Overvej følgende
mysql> select * from employee ;
+------+------+--------+
| id | name | skills |
+------+------+--------+
| 1 | xyz | 1,2,4 |
| 2 | abc | 1,3 |
| 3 | lmn | 1,2,3 |
+------+------+--------+
3 rows in set (0.00 sec)
mysql> select * from skillset ;
+------+----------+
| id | skillset |
+------+----------+
| 1 | Python |
| 2 | Java |
| 3 | C |
| 4 | PHP |
+------+----------+
4 rows in set (0.00 sec)
Denne struktur ligner din, og for at foretage forespørgsler i disse situationer kan vi dog bruge find_in_set
men det er ret ineffektivt, her er et par eksempler
mysql> select e.id,
e.name,
group_concat(s.skillset) as skillset
from employee e join skillset s
on find_in_set(s.id,e.skills) > 0
where find_in_set(1,e.skills) > 0
group by e.id ;
+------+------+-----------------+
| id | name | skillset |
+------+------+-----------------+
| 1 | xyz | Python,Java,PHP |
| 2 | abc | C,Python |
| 3 | lmn | Java,Python,C |
+------+------+-----------------+
3 rows in set (0.00 sec)
select e.id,
e.name,
group_concat(s.skillset) as skillset
from employee e
join skillset s on find_in_set(s.id,e.skills) > 0
where find_in_set(2,e.skills) > 0 group by e.id ;
+------+------+-----------------+
| id | name | skillset |
+------+------+-----------------+
| 1 | xyz | Python,PHP,Java |
| 3 | lmn | C,Java,Python |
+------+------+-----------------+
Nu ville en ordentlig normalisering gøre livet meget enklere og vil have følgende associationstabel
mysql> select * from employee_skills;
+------------+----------+
| idemployee | idskills |
+------------+----------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 3 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
+------------+----------+
At forespørge nu vil være meget mere effektivt i dette tilfælde
mysql> select e.id,
e.name,
s.skillset from employee e
join employee_skills es on es.idemployee = e.id
join skillset s on s.id = es.idskills where s.id = 1 ;
+------+------+----------+
| id | name | skillset |
+------+------+----------+
| 1 | xyz | Python |
| 2 | abc | Python |
| 3 | lmn | Python |
+------+------+----------+
Ved at bruge den sidste tilgang kunne mere komplekse beregninger udføres ret nemt.