In PostgreSQL I need to refactor a table (Purchases
); it has a foreign key to another table (Shop
). Instead I want two fields that keep the relatio
So it seems to me the piece you are missing is simply updating your purchases table to contain the information from your shop table. If that is correct then you could just update the table using the existing foreign key before you drop it:
UPDATE purchases SET (shop, shop_user) =
(SELECT name, user FROM shop
WHERE shop.id = purchases.shop_id);
Your seem to go the wrong way. Your original, normalized schema is typically superior. If you need to display shop / user, create a VIEW.
But you may have your reasons, so here goes:
UPDATE purchases p
SET (shop, shop_user) = (s.name, s."user")
FROM shop s
WHERE s.id = p.shop_id;
Don't use the reserved word "user"
as identifier.
And "name" is hardly ever a good name, either.
And varchar(255)
in Postgres typically indicates a misunderstanding.
varchar(255)