当一个字段是一组ID时,联接两个表

时间:2019-05-08 13:07:24

标签: mysql sql

我有两个表:

员工

Name | DepartmentId | Address | Phone number
--------------------------------------------
Tom  | [a1, b2] | 51 Rue Fort  | 123456
Ron  | [a1]    | San Picafort | 234566
Matt | [b2]    | Frank Road   | 523422 

部门

Id | Dept Name | Number of Employees | Location 
------------------------------------------
a1  | HR | 500 | Zambia
b2  | IT | 300 | Tanzania

我需要在DepartmentId上连接两个表,但是问题是EMPLOYEE表中的DepartmentId是一个数组。我无法在其上运行加入。喜欢:

select *
from EMPLOYEE,
     DEPARTMENT
where EMPLOYEE.DepartmentId = DEPARTMENT.id;

哪个将给出如下输出:

Name | DepartmentId | Address | Phone number | Dept Name | Number of Employees | Location 
---------------------------------------------------------------------
Tom | a1 | 51 Rue Fort | 123456 | HR | 500 | Zambia
Tom | b2 | 51 Rue Fort | 123456 | IT | 300 | Tanzania
Ron | a1 | San Picafort | 234566 | HR | 500 | Zambia
Matt | b2 | Frank Road | 523422 | IT | 300 | Tanzania

如何使用查询使EMPLOYEE表成为原子表,然后运行联接查询?

3 个答案:

答案 0 :(得分:0)

使用LIKE运算符创建内部联接

SELECT E.NAME,
E.DepartmentId,
E.Address,
E.[Phone number],
D.[Dept Name],
D.[Number of Employees],
D.Location 
FROM EMPLOYEE E
INNER JOIN DEPARTMENT D
    ON CAST(E.DepartmentId AS VARCHER(MAX)) LIKE '%' + CAST(D.id AS VARCHER(MAX))+ '%'

答案 1 :(得分:0)

数组很难处理,我不确定@mkRabbani是否使用LIKE有更快的解决方案,但是另一个更合适的选择是使用FIND_IN_SET()的联接。两者都效率极低,但是查询看起来像这样:

SELECT *
FROM EMPLOYEE E
INNER JOIN DEPARTMENT D
    ON FIND_IN_SET(D.Id, E.DepartmentId)

答案 2 :(得分:0)

我认为更干净的方法可能是有一个额外的表来表示EMPLOYEEDEPARTMENT之间的多对多关系。假设EMPLOYEE_DEPARTMENT。雇主与部门之间的每种关系都排成一行。当然,您也可以将ID添加到employee表中。我认为所有查询都会有所不同,但性能会更好。

表格将如下所示:

员工

Id | Name | Address     | Phone number
-----------------------------------
1 | Tom  | 51 Rue Fort  | 123456
2 | Ron  | San Picafort | 234566
3 | Matt | Frank Road   | 523422 

部门

Id | DeptName | Number of Employees | Location 
-----------------------------------------------
a1  | HR      | 500                 | Zambia
b2  | IT      | 300                 | Tanzania

EMPLOYEE_DEPARTMENT

Emp | Dept 
-----------
1  | a1
1  | b2
2  | a1 
3  | b2

您要查询的查询可能是:

Select E.*, D.Id from EMPLOYEE as E left join EMPLOYEE_DEPARTMENT as ED on E.Id=ED.Emp left join DEPARTMENT as D on ED.Dept=D.Id;

产生输出:

Id | Name | Address     | Phone number | Dept Name | Number of Employees | Location | DepartmentId  
---------------------------------------------------------------------------------------------------
1  | Tom   | 51 Rue Fort | 123456       | HR        | 500                 | Zambia   | a1  
1  | Tom   | 51 Rue Fort | 123456       | IT        | 300                 | Tanzania | b2 
2  | Ron   | San Picafort| 234566       | HR        | 500                 | Zambia   | a1
3  | Matt  | Frank Road  | 523422       | IT        | 300                 | Tanzania | b2

在输出中,您也可以将DepartmentId表的其他列更改为DEPARTMENT