INNER JOIN MULTIPLE COLUMN with ONE TABLE MYSQL

时间:2018-01-09 14:28:54

标签: mysql database inner-join

我有两个不同的表,一个包含类别ID和名称,另一个包含我的员工信息。员工可以拥有更多类别。

表格示例:

分类表:

IDCAT | Name
----------
 1 | Mechanic
 2 ! Office
 3 | Generic Mechanic

员工表:

ID | Name              | cat1 | cat2 | cat3
--------------------------------------------
 1 | Mechanic          |  1   |   2  |
 2 ! Office            |  1   |   3  |   
 3 | Generic Mechanic  |  1   |   2  |   3

我想用MySQL打印这样的表格,以便我可以在我的PHP脚本中打印它:

ID | Name              | cat1        | cat2                | cat3
--------------------------------------------------------------------------------
 1 | Mechanic          |  Mechanic   |  Office             |
 2 ! Office            |  Mechanic   |   Generic Mechanic  |   
 3 | Generic Mechanic  |  Mechanic   |  Office             |   Generic Mechanic 

我尝试使用此查询,但ID仅打印第一个类别名称

SELECT * FROM 'Employee' INNER JOIN category on Employee.cat1 = category.idcat

我可以做些什么来取得我的成绩,还是应该改变我的桌子? 感谢

2 个答案:

答案 0 :(得分:1)

SELECT
    e.ID
    ,e.Name
    ,c1.Name
    ,c2.Name
    ,c3.Name
FROM
    Employee AS e
    LEFT JOIN Category as c1 ON e.cat1 = c1.ID
    LEFT JOIN Category AS c2 ON e.cat2 = c2.ID
    LEFT JOIN Category AS c3 ON e.cat3 = c3.ID

请注意,您的Employee表结构很差。 通常,您将拥有一个单独的表来保存EmployeeID + CategoryID并添加外键。

A many to many tutorial可以在这里找到,并且可以让您更好地了解如何更好地构建表格。

答案 1 :(得分:0)

您应该规范化您的表Employee避免多个列类别,例如:

Category table:

IDCAT | Name
----------
 1 | Mechanic
 2 ! Office
 3 | Generic Mechanic
Employee table:

ID | Name              
----------------------
 1 | Emp1 Mechanic     
 2 ! Office            
 3 | Generic Mechanic 



Employee_category
id | id_emp | id_cat
-------------------------
1  ! 1      | 1
2  | 1      | 2
3  | 2      | 1
4  | 2      | 3
5  ! 3      | 1
6  | 3      | 2
7  | 3      ! 3

基于此架构,您可以使用group_concat获取与一行员工相关的所有类别

  select e.name, group_concat(c.name)
  from employee e
  inner join Employee_category ec on e.id = ec.id_emp
  inner join Caetgory c on c.idcat = ec.id_cat
  group by e.name