【发布时间】:2018-08-13 16:26:07
【问题描述】:
我在员工表中有 2 列,每列的值必须是唯一的(staff_code、staff_name)
| staff_id | staff_code | staff_name |
|-------------|------------|------------|
| 1 | MGT | Management |
| 2 | IT | IT staff |
在向表中插入或更新项目时,我必须检查 staff_code 和 staff_name 是否唯一。
在当前程序中,我使用 4 个函数来检查它。
- 插入时检查staff_code,
- 更新时检查staff_code
- 插入时检查人员姓名
- 更新时检查人员姓名
我已经包含了简化代码
检查功能1)
$SELECT * FROM staff WHERE staff_code = $staff_code
if num_of_rows > 0 //cannot insert, staff_type already exists
检查功能2)
从
获取当前员工类型$current_staff_type => SELECT * FROM staff WHERE staff_id = $staff_id
if($current_staff_type == $updated_staff_type){
//don't update
return
}
SELECT * FROM staff WHERE staff_type = $updated_staff_type
if(num_of_rows > 0){
//the type you're going to update already exists
return
} else{
//update
}
if num_of_rows > 0 //cannot insert, staff_type already exists
我对其他 2 也有类似的功能。 问题是我必须针对 4 个条件分别发送错误消息。 这是执行此操作的最佳做法吗? 除了多次访问数据库,我可以用另一种简单的方法吗?
【问题讨论】:
-
staff_name真的必须是唯一的吗?会有人在同一个地方工作,同名。 -
SELECT * FROM staff WHERE staff_type = $updated_staff_type OR staff_code = $staff_code用OR检查一次 -
你也可以在插入 SQL 中有一个子句,只在不存在的情况下执行,然后检查结果是否插入,这会在尝试插入之前保存初始查询
-
为什么不使用唯一索引?
-
确实 @Sakezzz 是对的,您当前的方法很容易出现称为 race condition 的情况