将关联记录复制到新表

问题描述 投票:0回答:1

我有四张桌子 - company_targetablesemployee_targetablesemployeesusers。我正在使用Postgresql 9.6。

架构:

company_targetables

  • id
  • company_id外键
  • name字符串
  • value - 字符串

employee_targetables

  • id
  • company_targetable_id外键
  • employee_id外键

employees - user_id

employee_targetablescompany_targetablesemployees之间的联盟。

我想分别将company_targetablesemployee_targetables移到新表custom_attributesuser_custom_attributes,保留关系,但是我想将user_custom_attributes记录与user外键关联,而不是将user_id与员工联系起来。

新表的模式:

custom_attributes

  • company_targetables的架构相同

user_custom_attributes

  • custom_attribute_id
  • user_id需要从旧表中的关联employee记录中获取用户ID

例如,如果我有一个与ID为1的employee_targetable关联的company_targetable,我可以很容易地复制company_targetable_id,但是我需要确保使用与custom_attribute相同的值创建相应的company_targetable记录,以便关系中的列值为保存。另外,我想确保新的user_custom_attribute记录用user_id值填充employees.user_id列。

目前,我正在做这个1比1 - 首先创建custom_attribute记录,然后从user_id抓住employee并创建user_custom_attribute记录,但有大约500,000条记录,这需要一段时间。

有没有办法有效地做到这一点?

sql postgresql
1个回答
0
投票

这就是我想出来的

首先复制从company_targetables到custom_attributes的所有内容:

      INSERT INTO custom_attributes(id, name, value, targetable, company_id, created_at, updated_at)
  SELECT company_targetables.id, company_targetables.name, company_targetables.value, 't',
         company_targetables.company_id, company_targetables.created_at, company_targetables.updated_at
  FROM company_targetables

然后从employee_targetables到用户自定义属性的所有内容,加入员工,以便我可以填写user_id列:

      INSERT INTO user_custom_attributes(id, custom_attribute_id, user_id, created_at, updated_at)
  SELECT employee_targetables.id, employee_targetables.company_targetable_id, employees.user_id,
         employee_targetables.created_at, employee_targetables.updated_at
  FROM employee_targetables
  INNER JOIN employees ON employees.id = employee_targetables.employee_id

大约500,000条记录花了22秒 - 这也许是批量更新的好方法。

© www.soinside.com 2019 - 2024. All rights reserved.