sql - 无论记录是否存在,插入并返回 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 条件的现有记录时它不返回任何内容。请指教。谢谢。
解决方案
您将使用 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
防止重复。
推荐阅读
- python - 在 python 中将生成器转换为 Numpy 数组
- python - 如何将 Plotly 升级到最新版本?
- python - 无法使用导出导出 Yolov5 模型
- ansible - Ansible Inventory:如何从不在某些其他组中的主机构建组
- javascript - Oracle APEX 警告消息
- r - 如何在函数中使用包含多个变量的选择?
- reactjs - 类型对象上不存在属性“过滤器”
- bootstrap-5 - 未捕获的类型错误:z.fn.dropdown 未定义
- macos - 您应该如何在 Metal 中正确编码大量 blit 或缩放命令?
- javascript - 如何覆盖html表中的数据并将此数据导出到现有的excel文件