我的要求是,如果记录不存在,则将记录插入表中,但无论记录是否存在,SQL都需要返回id。这是我的 SQL:
INSERT INTO tags (tag)
SELECT 'abc'
WHERE NOT EXISTS (SELECT 1 FROM tags WHERE tag = 'abc') RETURNING tag_id;
但它只在记录不存在时返回 id,当它有匹配 WHERE 条件的现有记录时它不返回任何内容。请指教。谢谢。
答案 0 :(得分:1)
您将使用 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
。
答案 1 :(得分:1)
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;