[英]How to insert an auto-generated id in a Postregsql entity table in another table's ID
I have an entity table that I want to auto-generate data from to use as FK in other tables.我有一个实体表,我想从中自动生成数据以在其他表中用作 FK。 The generated Id will become the PK in the other tables.
生成的 Id 将成为其他表中的 PK。
Users table with user_Id (PK), and other columns such as firstname , lastname , email , password etc.带有user_Id (PK) 的用户表,以及其他列,例如firstname 、 lastname 、 email 、 password等。
Entry table is the Entity table with one entry_Id (PK) column.条目表是具有一个entry_Id (PK) 列的实体表。
Article table will use the auto-generated entry_Id in Entry table above as PK with other columns such as title , authorId , category , created_Date . Article表将使用上面Entry表中自动生成的entry_Id作为 PK 与其他列,例如title , authorId , category , created_Date 。
Photo table will use the auto-generated entry_Id in Entry table above as PK with other columns such as title , imageurl , authorId (FK), created_Date .照片表将使用上面Entry表中自动生成的entry_Id作为 PK 与其他列,如title 、 imageurl 、 authorId (FK)、 created_Date 。
Comment table will use comment_Id as PK with the auto-generated entry_Id in Entry table above as FK to form a composite key.评论表将使用comment_Id作为PK,将上面Entry表中自动生成的entry_Id作为FK,形成一个复合键。 Other columns include user_Id as FK from Users table, comment , created_Date .
其他列包括来自Users表的user_Id作为 FK、 comment 、 created_Date 。
Flag table will use flag_Id as PK with the auto-generated entry_Id in Entry table above as FK to form a composite key. Flag表会使用flag_Id作为 PK,上面的Entry表中自动生成的entry_Id作为 FK,形成一个复合键。 Other columns include user_Id as FK from Users table, flag_type .
其他列包括来自用户表flag_type的user_Id作为 FK。
I want my query to auto-generate the entry_Id for entry when someone submit a form and automatically used the generated id in other tables such as Article , Photo , Comment and Flag .我希望我的查询在有人提交表单时自动生成entry_Id并在其他表(例如Article 、 Photo 、 Comment和Flag )中自动使用生成的 id 。
When I hard coded the values, the Article and Photo table is accepting one entry_Id for multiple rows.当我对这些值进行硬编码时, Article和Photo表接受一个entry_Id用于多行。
I saw something like this but I am not sure if it's what I want.我看到了这样的东西,但我不确定这是否是我想要的。
START TRANSACTION;
INSERT INTO foo (auto,text)
VALUES(NULL,'text');
INSERT INTO foo2 (id,text)
VALUES(LAST_INSERT_ID(),'text');
COMMIT TRANSACTION;
Is there a script I can use to make the auto-generated id in my entity table re-usable in other tables?是否有一个脚本可用于使我的实体表中的自动生成的 id 可在其他表中重复使用?
As commented by wildplasser, since version 9.1 Postgres has a nice feature that combines a cte with the returning
keyword, which allows you to do what you want.正如 wildplasser 所评论的,自 9.1 版以来,Postgres 有一个很好的功能,它结合了 cte 和
returning
关键字,它允许你做你想做的事。
Here is an example based on your pseudo-code:这是基于您的伪代码的示例:
with foo_row as (insert into foo (text) values ('text') returning foo_id)
insert into foo2 (foo_id) select foo_id from foo_row
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.