java - 唯一约束和程序查询是否存在的优缺点?
PHP中文网
PHP中文网 2017-04-18 10:03:43
0
3
368

我想要保持数据库记录的不重复,现在有两种方案,一种是给这一个(或多个)字段添加唯一性约束,一种是程序先去查询数据库是否存在给个字段值的记录,再决定是否插入?请问这两种方式该如何抉择?有更好的方式么?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
巴扎黑

Relying on program to ensure uniqueness is unreliable, because under high concurrency conditions, the following 2 steps will overlap, resulting in repeated insertion:

  1. Check whether there is already a record in the database

  2. If not, insert record

小葫芦

It is better to choose the unique constraint:

  • Simplify application logic.

  • When establishing a unique constraint, the system will usually automatically create an index to ensure uniqueness while increasing query performance. (PostgreSQL Documentation)

Adding a unique constraint will automatically create a unique B-tree
index on the column or group of columns listed in the constraint.

伊谢尔伦

The author understands what the purpose of the database is. The database system is developed from the file system. If you follow the second option, you can directly store it as a file. Why use a database? The database is not just simple SQL. As a DBMS, it also provides many other functions, allowing you to concentrate on solving application problems while optimizing the underlying access of the system.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!