【问题标题】:How to replace comma separated department ids with their name respectively?如何分别用他们的名字替换逗号分隔的部门 ID?
【发布时间】:2015-04-07 06:09:34
【问题描述】:

我的桌子是这些:

员工表:

+-----------+----------+------------+
| 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     |
+----+------------+-------------+

【问题讨论】:

  • 不要这样做。创建另一个表employee_department(employee_id, department_id) 将两个表链接在一起。
  • 我会说那只是糟糕的设计......
  • 好的,它不遵循规范化。但是有没有办法得到相同的答案?

标签: mysql join


【解决方案1】:

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

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

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
    

    【讨论】:

    • 在这个问题中,我相信只是作为一个例子,部门表显示了 2 条记录。使用您提供的解决方案,每次在部门表中添加/修改记录时,您都需要添加/修改替换语句
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    猜你喜欢
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    相关资源
    最近更新 更多