php - PHP MySQL SELECT中的嵌套if语句
问题描述
我需要交叉引用行。如果该行不存在,则插入它。
以下是在将其插入数据库之前需要通过的标准:
首先查找属于用户 (
user_id
) 的约会。然后查找与约会 ID (
appointment_id
) 匹配的约会。如果约会 ID 不存在,请继续下一步。如果约会 ID 不存在,则搜索约会是否与约会日期和时间匹配 (
appointment_date
) (appointment_time
)。如果它不存在,则
INSERT
进入数据库。
到目前为止,这是我的代码。如何使我的嵌套 if 语句SELECT
更快更简单?
// Search for appointment by appointment ID to see if it already exists
$stmt = $dbh->prepare("SELECT id FROM users WHERE user_id = :user_id AND appointment_id = :appointment_id LIMIT 1");
$stmt->bindParam(':user_id', $userId);
$stmt->bindParam(':appointment_id', $appointmentId);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// If appointment does not already exist, search for appointment by date and time
if(!$result) {
$stmt = $dbh->prepare("SELECT id FROM users WHERE user_id = :user_id AND appointment_date = :appointment_date AND appointment_time = :appointment_time LIMIT 1");
$stmt->bindParam(':user_id', $userId);
$stmt->bindParam(':appointment_date', $appointmentDate);
$stmt->bindParam(':appointment_time', $appointmentTime);
$stmt->execute();
$result2 = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$result2) {
// If appointment does not already exist, insert into database:
$stmt = $dbh->prepare("INSERT INTO...")
}
}
我怎样才能使它更快,更简单/更短?
解决方案
如果您不需要区分这两个查询,只需结合您的条件:
SELECT id FROM users WHERE user_id = :user_id AND
(appointment_id = :appointment_id OR
appointment_date = :appointment_date AND appointment_time = :appointment_time)
LIMIT 1
推荐阅读
- windows - 将 sh 文件设置为 git bash
- mysql - 在相对于 ID 的 2 个表之间选择同一行
- c# - 将授权(例如:Facebook)声明、身份验证令牌与内部用户帐户集成
- asp.net-web-api - 重复 ID 生成
- ios - avplayer 根据速率暂停或停止通知
- r - 根据它们在行中是最小的还是最大的来组织列中的数字
- c++ - 从字符串构建二叉树
- python-3.x - 当我再次关闭并打开笔记本时,在 Jupyter 笔记本中没有得到图表?
- c++ - C++ 使用 GMP 库生成随机素数
- mobile - 如何使 SemanticUI 下拉菜单在没有悬停的情况下工作(在移动设备上)?