插入(如果不存在)并返回ID [英] Insert (if not present) and return id

查看:110
本文介绍了插入(如果不存在)并返回ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个独特的专栏。我想插入一行(如果尚未插入),然后返回该行的 id

I have a unique column. I want to insert a row if it's not already there, and then return the id of that row.

INSERT INTO t(a) VALUES ('a') ON CONFLICT DO NOTHING RETURNING t.id;

什么也不返回。 这是一个小提琴

我正在寻找如何每次获取1,无论是否新插入了'a'。

returns nothing at all. Here's a fiddle.
I'm looking for how to get 1 each time, whether 'a' was newly inserted or not.

推荐答案

with i as (
    INSERT INTO t(a) VALUES ('a') ON CONFLICT (a) DO NOTHING RETURNING id
)
select id from i
union all
select id from t where a = 'a'
limit 1

这篇关于插入(如果不存在)并返回ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆