MySQL:识别重复项并替换值-初学者



平台:MySQL Workbench 8.0 CESQL:5.5.57

我在为以下任务创建正确的语句时遇到问题:

假设我们有一张"部门"表

| id | name | superior_dep_id |
_______________________________
1  | SM   |  null          
2  | SMT  |  1      
3  | SMTE |  2 
4  | SMI  |  1      
5  | SM   |  null 

我刚刚添加了一个新部门"SM",它将取代旧部门,仅就有效性而言,所以旧部门仍然保持不变。

现在,我需要识别所有部门,它们在departments.superior_dep_id处包含旧的departments.id,并用新的departments.id = 5替换它们。

| id | name | superior_dep_id |
_______________________________
1  | SM   |  null          
2  | SMT  |  1      <--- 5
3  | SMTE |  2 
4  | SMI  |  1      <--- 5
5  | SM   |  null   <--- INSERT INTO 
departments(id, name, superior_dep_id) 
VALUES(5, SM, null);

提前谢谢。

首先,我想您必须按名称识别最后插入的departments.id,跳过您插入的最后一个:

select departments.id from departments where name = 'SM' and departments.id <> 5 ORDER BY departments.id DESC LIMIT 1;

获得departments.id(将为1)后,您可以更新字段:

update departments set superior_dep_id = 5 where superior_dep_id = 1;

最新更新