如何将多个列从一个表移动到一个新的一对多表?

时间:2012-09-01 19:14:36

标签: sqlite refactoring

我想通过将一个表分成两个来重构我的数据库。我想将一些现有列移动到新表中。例如,假设我想将下面home_address表中的work_addressEmployee字段移动到新的Address表。

如何使用sqlite 完成

之前:

Employee Table
   employee_id (Primary)
   name
   home_address
   home_city
   work_address
   work_city

后:

Employee Table
   employee_id (Primary)
   name
   home_address_id
   work_address_id

Address Table
   address_id (Primary)
   address
   city

1 个答案:

答案 0 :(得分:1)

我更喜欢迁移简单明了,没有额外的逻辑等等。至少当你只运行一次左右时。

因此,首先检查什么是max(employee_id),下面假设它小于10000(并且它是整数)。

create table employee_new(employee_id,name,home_address_id,work_address_id);
insert into employee_new select employee_id,name,employee_id,employee_id+10000 from employee;
create table address(address_id,address,city);
insert into address select employee_id,home_address,home_city from employee; 
insert into address select employee_id+10000,work_address,work_city from employee; 
alter table employee rename to employee_old;
alter table employee_new rename to employee;