Postgresql用名称替换ID的最简单方法

时间:2019-01-23 11:42:57

标签: postgresql

在Postgresql中:

说我有一张桌子Dogs

SELECT * FROM "Dogs"
...
Name        OwnerID
'Pooch'     'OWR14'
'Sparky'    'OWR12'
'Pooch'     'OWR17'

还有一个表Owners

SELECT * FROM "Owners"
...
ID         Name
'OWR14'    'Peter'
'OWR12'    'Jack'
'OWR17'    'Mary'

OwnerID表中的Name值替换Owner字段的最快/最简单方法是什么?

我最快的方法:

SELECT "Dogs"."Name", "Owners"."Name" AS "Owner"
FROM "Dogs"
LEFT JOIN "Owners" ON "Dogs"."OwnerID" = "Owners"."ID"
...
Name        Owner
'Pooch'     'Peter'
'Sparky'    'Jack'
'Pooch'     'Mary'

1 个答案:

答案 0 :(得分:0)

查看示例可能是加入

的更新
UPDATE Dogs
SET Dogs.OwnerID = Owners.Name
FROM Owners
WHERE Dogs.OwnerID = Owners.id;

否则,如果您只需要更快的查询,请确保在Dogs表上具有正确的组合索引

CREATE INDEX my_idx1 on "Dogs" ("OwnerID", "Name" )

和表所有者

CREATE INDEX my_idx2 on "Owners" ("ID", "Name" )