插入并返回id,无论记录是否存在



我的要求是,如果记录不存在,就向表中插入一条记录,但无论记录是否存在,SQL都需要返回id。这是我的SQL:

INSERT INTO tags (tag)
SELECT 'abc'
WHERE NOT EXISTS (SELECT 1 FROM tags WHERE tag = 'abc') RETURNING tag_id;

但它只在记录不存在的情况下返回id,当它有符合WHERE条件的现有记录时,它不返回任何信息。请告知。谢谢

with
cte_sel(tag_id) as (
select tag_id from tags where tag = 'abc'),
cte_ins(tag_id) as (
insert into tags (tag)
select 'abc'
where not exists (select 1 from cte_sel)
returning tag_id)
select * from cte_sel
union all
select * from cte_ins;

您可以使用CTE来获取所有记录:

with to_insert as (
select 'abc' as tag
),
insert into tags (tag)
select tag
from to_insert
where not exists (select 1 from tags where tags.tag = to_insert.tag)
)
select *
from to_insert;

为了防止重复,我建议您使用on conflict而不是not exists

最新更新