鉴于以下结构:
表A(aliases):

user_id | alias
---------------
   1      john
   2      peter

user_idid中引用users
表B(users):
  id | password_hash | ...
---------------------------
   1        ...        ...
   2        ...        ...

(想法是用户可以有多个别名,所有别名都指向同一个主用户帐户记录)
我要执行以下操作:给定alias, password, ...记录:
如果alias存在于aliases,请更新password中对应的users
如果alias不存在,用给定的密码在users中创建一个新用户,并将一行插入到aliases指向这个新记录。
在Postgres中,如何在一个查询中做到这一点?
有点像
WITH (
  INSERT INTO users(id, password, ...) VALUES(DEFAULT, password, ...) RETURNING id
)
INSERT INTO aliases(user_id, alias) VALUES(id, alias)
  ON CONFLICT {delete the temp row in users and update the one with the
               known user_id instead}

最佳答案

这假设users_id_seq是用于users.id的序列,并且对UNIQUE有一个aliases.alias约束:

WITH a AS (INSERT INTO aliases (user_id, alias)
              VALUES (nextval('users_id_seq'), p_alias)
           ON CONFLICT (alias)
              /* this does nothing, but is needed for RETURNING */
              DO UPDATE
                 SET user_id = aliases.user_id
           RETURNING user_id
          )
INSERT INTO users (id, password_hash, ...)
   SELECT user_id, p_password, ...
      FROM a
ON CONFLICT (id)
   DO UPDATE
      SET password_hash = EXCLUDED.password_hash;

关于sql - 在PostgreSQL中插入表A期间如何有条件地在表B中插入记录?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43139908/

10-17 03:10