gpt4 book ai didi

PostgreSQL 自引用表 - 如何在脚本中存储父 ID?

转载 作者:行者123 更新时间:2023-12-04 12:50:46 34 4
gpt4 key购买 nike

我有下表:

DROP SEQUENCE IF EXISTS CATEGORY_SEQ CASCADE;
CREATE SEQUENCE CATEGORY_SEQ START 1;

DROP TABLE IF EXISTS CATEGORY CASCADE;

CREATE TABLE CATEGORY (
ID BIGINT NOT NULL DEFAULT nextval('CATEGORY_SEQ'),
NAME CHARACTER VARYING(255) NOT NULL,
PARENT_ID BIGINT
);

ALTER TABLE CATEGORY
ADD CONSTRAINT CATEGORY_PK PRIMARY KEY (ID);
ALTER TABLE CATEGORY
ADD CONSTRAINT CATEGORY_SELF_FK FOREIGN KEY (PARENT_ID) REFERENCES CATEGORY (ID);

现在我需要插入数据。所以我从 parent 开始:

INSERT INTO CATEGORY (NAME) VALUES ('PARENT_1');

现在我需要刚刚插入的父级的 ID 来向其添加子级:

INSERT INTO CATEGORY (NAME, PARENT_ID) VALUES ('CHILDREN_1_1', <what_goes_here>);
INSERT INTO CATEGORY (NAME, PARENT_ID) VALUES ('CHILDREN_1_2', <what_goes_here>);

我如何获取并存储父级的 ID,以便稍后在后续插入中使用它?

最佳答案

您可以使用带有 returning 子句的数据修改 CTE:

with parent_cat (parent_id) as (
INSERT INTO CATEGORY (NAME) VALUES ('PARENT_1')
returning id
)
INSERT INTO CATEGORY (NAME, PARENT_ID)
VALUES
('CHILDREN_1_1', (select parent_id from parent_cat) ),
('CHILDREN_1_2', (select parent_id from parent_cat) );

关于PostgreSQL 自引用表 - 如何在脚本中存储父 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39098722/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com