我想要保持数据库记录的不重复,现在有两种方案,一种是给这一个(或多个)字段添加唯一性约束,一种是程序先去查询数据库是否存在给个字段值的记录,再决定是否插入?请问这两种方式该如何抉择?有更好的方式么?
巴扎黑2017-04-18 10:05:43
Relying on program to ensure uniqueness is unreliable, because under high concurrency conditions, the following 2 steps will overlap, resulting in repeated insertion:
Check whether there is already a record in the database
If not, insert record
高洛峰2017-04-18 10:05:43
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.
伊谢尔伦2017-04-18 10:05:43
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.