2012-09-01 34 views
0

我想通过将一个表分成两个来重构我的数据库。我想将一些现有的列移动到一个新表中。例如,假设我想将表中的home_addresswork_address字段移动到新的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

如果你不介意的话,我想提出一点不同的重构:'(员工:EMPLOYEE_ID,姓名),地址类型(address_type_id,姓名),地址:和你的一样,Employee_Address(ADDRESS_ID,address_type_id ,employee_id)'。 – a1ex07

+0

@ a1ex07你的意思是说你可以添加不确定类型的地址,而无需进一步的模式修改? –

+0

准确。我会更进一步,摆脱'Employee',用'Party','PartyRole'替代它(其中一个角色将是员工)。 – a1ex07

回答

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

够简单! :) –

相关问题