用于将实体迁移到新表的 MySQL 查询

问题描述

在我们的数据库中,我们有几个表,其中实体有时会附加一个文件,因此它们有一个 file 列,用于存储磁盘上该文件名称

id      entity_name     file

123     document1       fdjie.txt     (from table documents)
456     employee1       null          (from table employees)
789     building1       sgrfe.txt     (from table buildings)

我创建了一个名为 files 的新表,我需要将所有填充了 file 列的实体“复制”到其中。最终,我将从所有原始表中删除 file 列。

files 表还必须有一个 rel_id 列和它来自的表的 table_name

id      table_name      rel_id      entity_name     file

234     documents       123         document1       fdjie.txt
235     buildings       789         building1       sgrfe.txt

因为'employee1'没有文件,当然不会有插入。

我该怎么做?我尝试了一个带有子选择的插入语句,但我意识到我需要一个循环之类的东西。我可以在 MysqL 中执行此操作吗?

解决方法

我不确定为什么需要循环,除非您有大量的源表。

这样的事情是否可以满足您的需求:

insert into files (table_name,rel_id,entity_name,file) 
  select * from (
    select 'documents',id,file from `documents` where file is not null
     union all
     select 'employees',file from `employees` where file is not null
     union all
     select 'buildings',file from `buildings` where file is not null
   ) as a ;