PostgreSQL:当父表已经存在时,将记录插入子表中

发布于 2025-02-11 20:07:16 字数 871 浏览 1 评论 0原文

我有两个表格上有一个记录,我想在记录上创建一个子记录。我所做的详细信息如下:

使用串行PK创建两个表。

CREATE TABLE IF NOT EXISTS public.parent
(
    parent_id smallserial NOT NULL,
    parent_field character varying(64),
    PRIMARY KEY (parent_id)
)


CREATE TABLE public.child
(
    child_id smallserial,
    child_field character varying(64),
    PRIMARY KEY (child_id)
)
    INHERITS (public.parent);

然后执行a:

INSERT INTO parent (parent_field) VALUES ('Hello World');

序列给出的ID为4。然后,我尝试运行此查询以在子表上的该字段上构建:

INSERT INTO child (parent_id, parent_field, child_field)
VALUES (4, 'Hello World', 'The child');

但是我最终在父表上获得了两个记录:

如果我只想在该PK上拥有一个父记录,那么正确的方法是什么?

I have two tables where there is a record on the parent table where I want to create a child record that builds on the record. The detail of what I did is below:

Having two tables created with a serial PK.

CREATE TABLE IF NOT EXISTS public.parent
(
    parent_id smallserial NOT NULL,
    parent_field character varying(64),
    PRIMARY KEY (parent_id)
)


CREATE TABLE public.child
(
    child_id smallserial,
    child_field character varying(64),
    PRIMARY KEY (child_id)
)
    INHERITS (public.parent);

And then carrying out a:

INSERT INTO parent (parent_field) VALUES ('Hello World');

The ID the sequence gave was 4. I then tried running this query to build on that field on the child table:

INSERT INTO child (parent_id, parent_field, child_field)
VALUES (4, 'Hello World', 'The child');

But I ended up with two records on the parent table:
enter image description here

If I only want to have one parent record with that PK, what is the proper way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文