我有两个表,如下所示。在employee表中,而不是直接提及技能,我将其用作其他表的参考。
问题 :
select * from Employee where Skills = "1";
上面的查询将显示仅具有“ Python”技能的员工记录。当然,它不会显示包含Python的其他组合,例如“ 1,2”(Python,Java)。如果不使用类似的运算符,我怎么能做到这一点,因为如果我有10、11、21的技能,那就不是问题了。
如果您觉得这种使用参考的方法很困难或不建议使用,请提出您的想法:-)
员工表:
+-----+-------------+-------------+ | id | Name | Skills | +-----+-------------+-------------+ | 1 | Xyz | 1,2,4 | | 2 | Xyy | 1,3 | | 3 | Abc | 1,2,3 | | 4 | Asd | 1 | +-----+-------------+-------------+
技能表:
+-----+-------------+ | id | SkillSet | +-----+-------------+ | 1 | Python | | 2 | Java | | 3 | C | | 4 | PHP | +-----+-------------+
考虑以下
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)
这种结构与您的结构相似,但是在这种情况下可以进行查询,但是我们可以使用,find_in_set但是效率很低,这里有几个示例
find_in_set
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 | +------+------+-----------------+
现在,适当的规范化将使生活变得更加简单,并将具有以下关联表
mysql> select * from employee_skills; +------------+----------+ | idemployee | idskills | +------------+----------+ | 1 | 1 | | 1 | 2 | | 1 | 3 | | 2 | 1 | | 2 | 3 | | 3 | 1 | | 3 | 2 | | 3 | 3 | +------------+----------+
现在,在这种情况下执行查询将更加高效
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 | +------+------+----------+
使用最后一种方法,可以很容易地完成更复杂的计算。