【问题标题】:postgres - insert gen_random_uuid() for the column "key" if the count(key) < 1postgres - 如果 count(key) < 1,则为“key”列插入 gen_random_uuid()
【发布时间】:2018-02-19 00:09:57
【问题描述】:

如果有count(key) &lt; 1,则为key 列生成gen_random_uuid()

我的table 名字是keytablecolumnkey

我正在使用下面的insert 语句来生成 uuid :这是表中唯一的值。

INSERT INTO keytable VALUES(gen_random_uuid());

key 
--------------------------------------- 
5686473e-add1-4ab1-be85-7e62152ce539

我只想在我的“键”列中没有任何值时运行此 insert 语句。

换句话说,如果count(key) &lt; 1 那么我想运行INSERT INTO keytable VALUES(gen_random_uuid()); 请帮忙。

【问题讨论】:

  • 您提供的密钥是gen_random_uuid 的所需值吗?...它是什么?...

标签: postgresql-9.4


【解决方案1】:

Clodoaldo Neto 已经回答(链接如下)

here is according to your perspective

insert into keytable
select gen_random_uuid()
where not exists ( select key from keytable );

只插入select语句的结果

select key from keytable

这不会返回任何东西!

更多信息:https://stackoverflow.com/a/15710598/8506841

【讨论】:

  • @Aby 如果您的问题解决了!请接受它作为您的答案。
【解决方案2】:

改用INSERT ... SELECT 构造

t=# begin; insert into keytable select gen_random_uuid() where (select count(key) from keytable) < 1;
BEGIN
INSERT 0 1
t=# insert into keytable select gen_random_uuid() where (select count(key) from keytable) < 1;
INSERT 0 0
t=# rollback;
ROLLBACK

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    相关资源
    最近更新 更多