首页 > 解决方案 > 无论记录是否存在,插入并返回 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 条件的现有记录时它不返回任何内容。请指教。谢谢。

标签: sqlpostgresql

解决方案


您将使用 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防止重复。


推荐阅读