在另一个表中的一行的UPDATE中使用同一个表中的多个行

时间:2013-03-26 01:55:40

标签: sql postgresql sql-update postgresql-9.1

我正在使用pgadmin for PostgreSQL(9.1),我有这个查询需要很长时间才能运行

update tableA a
set owner1_surname = (select owner_surname from owners_distinct b where a.owner1= b.owner),
owner1_othername   = (select owner_othername from owners_distinct b where a.owner1= b.owner),
owner2_surname     = (select owner_surname from owners_distinct b where a.owner2= b.owner),
owner2_othername   = (select owner_othername from owners_distinct b where a.owner2= b.owner),
owner3_surname     = (select owner_surname from owners_distinct b where a.owner3= b.owner),
owner3_othername   = (select owner_othername from owners_distinct b where a.owner3= b.owner)

不必一次又一次地从owners_distinct table检索值,是否可以使用{{1}检索列ownerowner_surnameowner_othername一次然后根据检查在SELECT的列上执行UPDATE

2 个答案:

答案 0 :(得分:1)

这比我想象的要复杂,因为你想多次加入同一个表,唯一的连接是更新的表本身:

UPDATE table_a a
    SET owner1_surname = b1.owner_surname
    ,owner1_othername  = b1.owner_othername
    ,owner2_surname    = b2.owner_surname
    ,owner2_othername  = b2.owner_othername
    ,owner3_surname    = b3.owner_surname
    ,owner3_othername  = b3.owner_othername
FROM   table_a x
LEFT   JOIN owners_distinct b1 ON b1.b.owner = x.owner1
LEFT   JOIN owners_distinct b2 ON b2.b.owner = x.owner2 
LEFT   JOIN owners_distinct b2 ON b3.b.owner = x.owner3
WHERE  x.table_a_id = a.table_a_id

其中table_a_idtable_a的主键。通常情况下,您不必再次加入表格,但在这种情况下,您需要在之前连接到更新的表格。

我使用LEFT JOIN,以防止在owners_distinct中找不到三个所有者之一时,行的整个更新失败。

数据库设计

您确定需要table_a中的所有冗余数据吗?规范化模式中的规范方法是仅存储foreign keysowner1owner2owner3),并根据需要获取名称的详细信息{{ 1}}在JOIN中。删除所有正在更新的列。当然,规则总是有例外......

没有唯一的密钥?

这应该不会开始。您应该添加代理主键,如:

SELECT

有关答案的更多相关内容:
Do I need a primary key for my table, which has a UNIQUE (composite 4-columns), one of which can be NULL?

没有唯一键的解决方案

无论如何,无论任何唯一列,都可以通过以下方式进行此更新:

ALTER TABLE table_a ADD table_a_id serial PRIMARY KEY;

重点是:我们只需要UPDATE table_a a SET owner1_surname = b1.owner_surname ,owner1_othername = b1.owner_othername ,owner2_surname = b2.owner_surname ,owner2_othername = b2.owner_othername ,owner3_surname = b3.owner_surname ,owner3_othername = b3.owner_othername FROM (SELECT DISTINCT owner1, owner2, owner3 FROM table_a) x LEFT JOIN owners_distinct b1 ON b1.b.owner = x.owner1 LEFT JOIN owners_distinct b2 ON b2.b.owner = x.owner2 LEFT JOIN owners_distinct b2 ON b3.b.owner = x.owner3 WHERE x.owner1 = a.owner1 AND x.owner2 = a.owner2 AND x.owner3 = a.owner3; 的每个组合一次。

答案 1 :(得分:-1)

SELECT owner,owner_surname和owner_othername FROM table_a

更新table_a a

 SET owner1_surname = b1.owner_surname
,owner1_othername  = b1.owner_othername
,owner2_surname    = b2.owner_surname
,owner2_othername  = b2.owner_othername
,owner3_surname    = b3.owner_surname
,owner3_othername  = b3.owner_othername