Home  >  Article  >  Backend Development  >  mysql insert problem

mysql insert problem

WBOY
WBOYOriginal
2016-08-20 09:04:001026browse

Two users insert a piece of data at the same time,
insert into table set name='tom',num=2
insert into table set name='jack',num=2
, but the business logic does not allow the num value to appear repeatedly.
How to restrict MySQL from inserting duplicate data?
1. Add a joint unique index, but the program will report an error, which seems unfeasible.
Is there any other method?

Reply content:

Two users insert a piece of data at the same time,
insert into table set name='tom',num=2
insert into table set name='jack',num=2
, but the business logic does not allow the num value to appear repeatedly.
How to restrict MySQL from inserting duplicate data?
1. Add a joint unique index, but the program will report an error, which seems unfeasible.
Is there any other method?

Use a unique index, use transaction processing in the insertion scenario, and throw a transaction reminder if there is a duplicate value.

The program reports an error?
You just need to catch the corresponding exception, then return and make a business explanation.

insert ignoreCan’t you?

That is, before each insertion, you have to check whether the num field in the table contains the value to be inserted; and consider the concurrency situation. Right? Either use mysql transactions; or mysql lock table mechanism

It is recommended that the database have its own verification mechanism, just like your unique constraint or index. The application can capture the error information of the database and provide corresponding explanations.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn