在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'
答案 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" )