简体   繁体   English

使用触发器将Postgres SQL插入语句拆分为2个表

[英]Splitting a postgres SQL insert statement into 2 tables using triggers

Is it possible to use postgres triggers to split an INSERT statement into 2 tables? 是否可以使用postgres触发器将INSERT语句拆分为2个表? So if you do insert into testtable (col1, col2) values (val1a, val1b), (val2a, val2b) , can it be translated with triggers to something like 因此,如果您确实insert into testtable (col1, col2) values (val1a, val1b), (val2a, val2b) ,是否可以将其与触发器转换为类似

insert into testtable (col1) values (val1a), (val1b)
insert into anothertable (col2) values (val2a), (val2b)

Basically is it possible for testtable to not have a col2 even though the original SQL INSERT looks like col2 should exist on testtable ? 基本上是有可能testtable不具有col2即使原始SQL INSERT看起来像col2上应该存在testtable

How can this be accomplished using triggers? 如何使用触发器来完成?

You can have a VIEW with either triggers or rules to redirect the INSERT . 您可以使用带有触发器或规则的VIEW来重定向INSERT

Or you can do it in a single SQL statement with data-modifying CTEs. 或者,您也可以在一个带有数据修改CTE的SQL语句中完成此操作。

WITH input(col1, col2) AS (
   VALUES
     (text 'val1a', text 'val1b')  --  explicit type cast in first row
   , ('val2a', 'val2b')
   )
, ins1 AS (
   INSERT INTO testtable (col1)
   SELECT col1 FROM input
   )
INSERT INTO anothertable (col2)
SELECT col2 FROM input;

Typically, one would also store the connections between 'val1a' and 'val1b' of your input row somehow . 通常,还会以某种方式存储输入行的“ val1a”和“ val1b”之间的连接。
You might want to use a RETURNING clause to get a serial PK from the first table and store that in the second table. 您可能想使用RETURNING子句从第一个表中获取串行PK并将其存储在第二个表中。

Related: 有关:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM