简体   繁体   English

插入前检查是否存在记录

[英]Check is record exists before inserting

I have a php script to insert new parts into a postgres database. 我有一个PHP脚本将新部件插入postgres数据库。 I want to check if the part exists before it is created. 我想在创建之前检查零件是否存在。 How can I do this. 我怎样才能做到这一点。 I am using the usual INSERT INTO clause. 我使用通常的INSERT INTO子句。

You SELECT first, to know if you must INSERT or UPDATE , like: 首先SELECT ,以了解是否必须INSERTUPDATE ,如:

if (
    $db->fetchOne(
        'SELECT COUNT(1) FROM parts WHERE article_number = ?',
        $p->article_number
    )
) {
    $db->update(
        'parts',
        $p->to_array(),
        $db->quoteInto('article_number = ?', $p->article_number)
    );
}
else {
    $db->insert('parts', $p->to_array());
}

Re Milen's comment: great point! Re Milen的评论:好点! With the default PostgreSQL transaction isolation level ( READ COMMITTED ) it's possible that another process inserts (and commits) "your" part after your SELECT , but before your INSERT . 使用默认的PostgreSQL事务隔离级别( READ COMMITTED ),另一个进程可能会在SELECT之后但在INSERT之前插入(并提交)“您的”部分。

For the kind of apps we build, we normally just catch the DB exception, and do something about it (inform the user, retry). 对于我们构建的应用程序类型,我们通常只捕获数据库异常,并对其执行某些操作(通知用户,重试)。 Or you can go with SET TRANSACTION ISOLATION LEVEL SERIALIZABLE . 或者你可以使用SET TRANSACTION ISOLATION LEVEL SERIALIZABLE See Transaction Isolation . 请参阅事务隔离

insert into parts(article_number,category) 
select 'KEYB','COMPTR' 
where not exists(select * from parts where article_number = 'KEYB')

If you rarely expect conflicts: Take the optimistic approach and just insert the new one and handle the uniqueness violation if it occurs. 如果您很少发生冲突:采用乐观方法,只需插入新方法并处理唯一性违规(如果发生)。 This will invalidate the current transaction when it fails, so if you're doing a lot of work in it, it'll be worthwhile to check first. 当它失败时,这将使当前事务无效,因此如果你正在做很多工作,那么首先检查是值得的。 In that case, I prefer SELECT EXISTS(SELECT 1 ... FROM ... WHERE ...) . 在这种情况下,我更喜欢SELECT EXISTS(SELECT 1 ... FROM ... WHERE ...)

Anyway, you must handle the possibility for a uniqueness violation. 无论如何,您必须处理违反唯一性的可能性。 Even if you check first, there is a possibility that a concurrent transaction inserts the same record and commits first. 即使您先检查,并发事务也有可能插入相同的记录并首先提交。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM