I have a table with a codigo
column. I can not set it as primary key. On a system that receives many notifications before it checks with a SELECT
to see if that code already exists in the table. If it does not exist it gives INSERT
and if it does it UPDATE
.
It turns out that this system receives many notifications via POST
where many of them happen at the same time for the same code.
Often the system, even giving SELECT
before, ends up inserting duplicate codes into the table.
I do not know how MySQL handles this, so I do not know if it's safe to make a% checker% before SELECT
. I assume that there is a sort of query queue and that it is being processed one by one.
$rs = $db->query("SELECT COUNT(1) AS tem_codigo FROM tabela WHERE codigo = $codigo");
if ($rs['tem_codigo'] == 0){
// aqui daria o insert
} else {
// aqui daria o update
}
How would a code above allow you to enter two records with equal codes? Imagine a request with a notification going on at the same time, at exactly the same time.
What is the best way to get around this without using a primary key?