【发布时间】:2023-04-03 01:37:01
【问题描述】:
我需要交叉引用行。如果该行不存在,则插入它。
以下是在将其插入数据库之前需要通过的条件:
首先查找属于用户 (
user_id) 的约会。然后查找与约会 ID (
appointment_id) 匹配的约会。如果约会 ID 不存在,请继续下一步。如果约会 ID 不存在,则搜索约会是否匹配约会日期和时间 (
appointment_date) (appointment_time)。如果不存在,则将
INSERT放入数据库。
到目前为止,这是我的代码。如何使 SELECT 的嵌套 if 语句更快、更简单?
// 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...")
}
}
我怎样才能让它更快、更简单/更短?
【问题讨论】:
-
如果尚未创建约会 ID,您如何获得它?
-
@Devon 约会 ID 来自另一个日历。我正在尝试同步两个日历
-
考虑使用 IODKU
标签: php mysql performance select pdo