【问题标题】:How can i insert into table on the basis of a column value is same or not in Postgresql如何根据 Postgresql 中的列值是否相同而插入表中
【发布时间】:2020-04-15 22:12:15
【问题描述】:

我正在向表中插入数据,如下所示

|   num   | name     |  value |
----------------------------------
|    1    | name1    |   1    |
|    2    | name2    |   1    |
|    3    | name3    |   1    |
|    4    | name4    |   2    |
|    5    | name5    |   3    |

我想在任意行中插入类似 insert into table (num, name, value) values(6,name,1) when (num and value together) not exist 的 where 子句

我尝试先选择并根据该结果插入,但我认为这不是我在单个查询中想要的最佳方式

尝试过:select * from the table where name=$name and value= $value if I got result then not insert otherwise insert. 它是通过两个查询完成的,但我不想要它。

如有任何帮助,将不胜感激。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    使用唯一约束来强制(num, value) 的唯一性:

    alter table t add constraint unq_t_num_value unique (num, value);
    

    然后数据库确保表的完整性——即这些值是唯一的。你不必明确地这样做。

    请注意,如果违反了唯一约束,您会收到错误消息,并且insert 将被中止(以及可能插入的其他行)。如果您想忽略错误,可以使用on conflict ignore

    【讨论】:

    • 如果尝试插入并违反唯一性怎么办。将插入或不插入其他没有唯一值的行,如果有错误我怎样才能插入 id 我想要一个简单的查询而不做唯一性你能告诉我@Gordon Linoff
    • @bala 。 . .正如答案中所指出的,您可以使用on conflict 来忽略错误。
    • 有一个问题....自动增量增加了它是否插入。我的意思是不插入但自动增量增加的冲突@Gordon Linoff
    【解决方案2】:

    基本上,首先您需要检查具有相同 num 和 Value 的记录是否已经存在于表中。如果存在则不插入,否则插入新记录。

    为此,您可以尝试使用过程插入值:

    以下过程将根据您的需要提供帮助:

    create procedure InsertRecVali(@num int,@name varchar(max),@value int)
    
    as 
    
    begin
    
    if not exist(select 1 from table where num=@num and value=@value)
    
    insert into table values(@num,@name,@value)
    
    Else 
    
    PRINT 'Cannot Insert Duplicate Value'
    
    End;
    

    创建过程后,通过传递要插入表中的值来执行此过程。

    所以在向表中插入记录之前,它会检查表中是否已经存在具有相同 numvalue 的记录,然后它不会插入它并给出错误' 无法插入重复值'。

    否则,如果具有相同numvalue的记录尚未出现在表中,则只有它会在表中插入记录。

    以下是执行此过程的示例:

    EXEC dbo.InsertRecVali(1,'abc',6)
    

    【讨论】:

    • 除了这应该使用unique index 来完成之外,这个特定的存储过程是一个竞争条件,将导致duplicate values 在高负载下插入。也就是说,如果它是 SQL Server,它会,但 OP 询问 PostgreSQL,这种语法在哪里甚至不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    相关资源
    最近更新 更多