gpt4 book ai didi

php - 在没有 like 运算符的情况下检索多个单个或引用的数据

转载 作者:行者123 更新时间:2023-11-29 01:55:44 24 4
gpt4 key购买 nike

我有两个表,如下所示。在员工表中而不是直接提及技能,我使用另一个表作为引用。

问题:

select * from Employee where Skills = "1";

上面的查询将显示只有“Python”技能的员工记录。当然,它不会显示包含Python的其他组合,例如“1,2”(Python,Java)。我如何在不使用 like 运算符的情况下实现这一目标,因为如果我的技能为 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来做查询,但是效率很低,这里有几个例子

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 |
+------+------+----------+

使用最后一种方法可以很容易地完成更复杂的计算。

关于php - 在没有 like 运算符的情况下检索多个单个或引用的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29891522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com