使用1个查询或函数更新多个Postgres表

时间:2016-05-03 15:14:18

标签: sql database postgresql

我有三个不同的表,我希望与Postgres同时更新所有这三个表。我想使用1个单一查询(无论是事务还是存储过程/函数)来更新所有查询。

我曾考虑将所有内容放入视图中,并创建规则来更新视图,但我不确定这是否是最有效的更新方式。我将以下“SELECT”查询中的所有信息都提取到前端的表单中。我想更新任何/所有更改的数据。例如,如果我更新实体,名字和角色,我想更新所有相应的表。

问题:如何通过1次调用数据库来更新所有三个表?如果那是不可能的,那么同时更新所有三个的最有效方法是什么?

目前,提取所有数据的查询如下:

SELECT u.user_id, u.firstname, u.lastname, r.role_name as role, u.username, e.entity 
FROM users u 
  INNER JOIN roles r  ON u.role_id = r.role_id 
  INNER JOIN entities e ON u.entity_Id = e.entity_Id 
WHERE u.user_id =1

参考表:

用户

        Column        |           Type           |
----------------------+--------------------------+
 user_id              | integer                  |
 firstname            | character varying(50)    |
 lastname             | character varying(50)    |
 role_id              | integer                  |
 entity_id            | integer                  |

Foreign-key constraints:
    "entity_fk" FOREIGN KEY (entity_id) REFERENCES entities(entity_id)
    "role_fk" FOREIGN KEY (role_id) REFERENCES roles(role_id)
Referenced by:
    TABLE "entities" CONSTRAINT "entities_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(user_id)
    TABLE "roles" CONSTRAINT "roles_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(user_id)

角色

  Column   |         Type          |
-----------+-----------------------+
 role_id   | integer               |
 role_name | character varying(50) |
 user_id   | integer               |

Foreign-key constraints:
    "roles_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(user_id)
Referenced by:
    TABLE "users" CONSTRAINT "role_fk" FOREIGN KEY (role_id) REFERENCES roles(role_id)

实体

    Column     |         Type          |
---------------+-----------------------+
 entity_id     | integer               |
 entity        | character varying(50) |
 user_id       | integer               |

Foreign-key constraints:
    "entity_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(user_id)
Referenced by:
    TABLE "users" CONSTRAINT "entity_fk" FOREIGN KEY (entity_id) REFERENCES entities(entity_id)

0 个答案:

没有答案