I know this question has been asked earlier and I have also read the documentation. But I guess I'm stupid not understand.
I have a code that inserts a row and the row should be unique in several field values. But to make this new data really live delivered to the visitors it updates (if new data, inserting it) via ajax and every 5th second. This means it sometimes insert two or more rows at the same time.
I have a SELECT
query before the INSERT
to check if the row (a row with the exactly same data) already exist. And I also use BEGIN
and COMMIT
.
Yet duplicate rows appearing.
I'm using innoDB.
I have googled and found LOCK
functions but not figured out how to use it. And does it even work for SELECT
? The best would be to LOCK the SELECT
query checking if the row already exist.
Best Answer
With
LOCK
you probably mean locking entire table, that should not be needed in InnoDB. Check SELECT .. FOR UPDATE.But duplicate values should be forbidden with the use of
UNIQUE
indexes, that way the worst thing you get is an "duplicate key" error and not a duplicated row.If you have proper indexes in place, you may even use INSERT .. ON DUPLICATE KEY UPDATE.