首页 > 解决方案 > 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...")
    }
}

我怎样才能使它更快,更简单/更短?

标签: phpmysqlperformanceselectpdo

解决方案


如果您不需要区分这两个查询,只需结合您的条件:

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

推荐阅读