How to replace comma separated department ids with their name respectively?

浪子不回头ぞ 提交于 2020-12-26 05:06:45

问题


My tables are these :

Employee Table:

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

Department Table:

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

Wanted output from employee table and department table :

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

回答1:


You should avoid storing data as comma-separated values, and follow normalization.

However in this case you can do something as

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 ;



回答2:


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


来源:https://stackoverflow.com/questions/29484913/how-to-replace-comma-separated-department-ids-with-their-name-respectively

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!