如何用他们的名字分别替换逗号分隔的部门ID?

时间:2015-04-07 06:09:34

标签: mysql join

我的表格是这些:

员工表:

+-----------+----------+------------+
| id       | name     | department  |
+-----------+----------+------------+
| 1        | Carrera  | 1           |
| 2        | Taylor   | 1,2         |
+-----------+----------+------------+

部门表:

+--------+-------+
| id     | name  |
+--------+-------+
|   1    |  CS   |
|   2    |  IT   |
+--------+-------+

来自员工表和部门表的通缉输出:

+----+------------+-------------+
| id | name       | department  |
+----+------------+-------------+
|  1 | Carrera    |   CS        |
|  2 | Taylor     |   CS,IT     |
+----+------------+-------------+

2 个答案:

答案 0 :(得分:2)

您应避免将数据存储为以逗号分隔的值,并遵循规范化。

但是在这种情况下,你可以做一些事情

select 
e.id , 
e.name , 
group_concat(d.name) from employee e 
left join department d on find_in_set(d.id,e.department) 
group by e.id ;

答案 1 :(得分:0)

SELECT replace(replace(department,'1','CS'),'2','IT')  as dept  from Employee