轻松地重新索引我的表格

时间:2013-06-23 15:12:44

标签: postgresql

美好的一天,

我目前正在使用posgresql作为我的后端,我必须对我的表字段进行大量更改。 我将使用两张桌子。

Table 1         Table 2

Old Index       New Index
Product Id      Old  Index
Address         Product Id
Contact no      Address
                Contact no
                Email

我必须从表2中迁移表1中的所有细节。我在表2中使用了不同的索引。 为了我的其他表识别我的旧索引我使用了这个查询

Update Table 2 Set  OldIndex =Table2.index
From(select  Oldindex  from Table 1)as  new,Table 1
Where  Table1.Productid =Table2.Productid

我有其他与表1相关的表,所以我的目标是用新索引替换旧索引,并希望其他表也可以看到更改。 但我不确定我做得对。我的查询很慢,我希望有人可以测试我的查询并指出我正确的方向,如果我做错了,请提前谢谢。

2 个答案:

答案 0 :(得分:1)

你介意尝试MERGE

MERGE INTO Table2 AS b
USING Table1 AS p
ON p.product_id = b.product_id
WHEN MATCHED THEN b.OldIndex = b.NewIndex

我不知道它对postgresql的作用,但你可以在这里找到一些样本:https://wiki.postgresql.org/wiki/MergeTestExamples

答案 1 :(得分:0)

在PostgreSQL中执行此操作的方法是使用可写CTE(在9.2及更高版本中可用)。

通过这种方式,您可以执行以下操作:

WITH up (UPDATE table2
            SET ....
           FROM table1 t1
          WHERE t1.product_id = table2.product_id
         RETURNING product_id)
 INSERT INTO table2 (...)
 SELECT ... 
   FROM table1 
  WHERE product_id NOT IN (select product_id from up);

您可以找到一些示例here