问题
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