-1

在我们的数据库中,我们有一些表,其中的实体有时会附加一个文件,因此它们有一个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 中执行此操作吗?

4

1 回答 1

0

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

这样的事情会做你需要的吗:

insert into files (table_name, rel_id, entity_name, file) 
  select * from (
    select 'documents', id, entity_name, file from `documents` where file is not null
     union all
     select 'employees', id, entity_name, file from `employees` where file is not null
     union all
     select 'buildings', id, entity_name, file from `buildings` where file is not null
   ) as a ;
于 2021-06-28T01:04:16.277 回答