我有一个用户和一个日志表。我想继续添加新日志,如果用户中不存在用户名,也要添加。
但是,如果用户不存在,我只会插入日志。如果用户已存在,则不添加任何日志。
如何解决这个问题以使其按预期工作?提前致谢。
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;
而不是上面,首先创建两个表,然后编写一个具有参数的存储过程。在该过程中,检查之前是否使用过该名称,如果一切正常,请保存。
这是常用的方法。如果你想,我也可以写一个程序。