Refactor foreign key to fields

前端 未结 2 1951
庸人自扰
庸人自扰 2020-12-07 02:46

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

2条回答
  •  旧时难觅i
    2020-12-07 03:36

    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.

    About varchar(255):

    • Should I add an arbitrary length limit to VARCHAR columns?
    • Any downsides of using data type "text" for storing strings?
    • More details in the manual.

提交回复
热议问题