[英]Second table does not get inserted if first table already exist
我有一个用户和一个日志表。 我想继续添加新日志,如果用户名不存在,请添加它。
但是,如果用户不存在,我所拥有的只会插入日志中。 如果用户已经存在,则不会添加任何日志。
如何解决此问题以使其按预期工作? 提前致谢。
CREATE TABLE user (
id serial NOT NULL,
name char(60) NOT NULL,
CONSTRAINT user_pk PRIMARY KEY (id),
CONSTRAINT user_un UNIQUE (name)
)
CREATE TABLE log (
id serial NOT NULL,
name_id int NOT NULL,
detail char(512) NULL,
CONSTRAINT detail_pk PRIMARY KEY (id),
CONSTRAINT detail_user_fk FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE RESTRICT ON UPDATE RESTRICT
)
我的尝试
with ins1 as (
insert into user (name)
values ('myname')
on conflict do nothing
returning id as user_id
)
insert into detail (user_id, detail)
select user_id, 'some detail' from ins1;
以下是我更改的其他问题的示例,更改了false却不做任何 更新 ,但仍未插入日志
with ins1 as (
insert into "user" (name)
values ('myuser')
on conflict (name) do update
set name = null where FALSE
returning id as user_id
)
insert into log (user_id, detail)
select user_id, 'some description' from ins1;
代替上面的方法,首先创建两个表,然后编写一个具有参数的存储过程。 在该过程中,请检查是否以前使用过该名称,如果一切正常,请保存它。
那是常见的方法。 如果您愿意,我也可以编写一个程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.