PHP MySQL SELECT中的嵌套if语句

PHP MySQL SELECT中的嵌套if语句,php,mysql,performance,select,pdo,Php,Mysql,Performance,Select,Pdo,我需要交叉引用行。如果该行不存在,则插入该行 在将其插入数据库之前,需要通过以下标准: 首先查找属于该用户的约会(user\u id) 然后查找与约会ID匹配的约会(appointment\u ID)。如果约会ID不存在,请继续下一步 如果约会ID不存在,则搜索约会是否与约会日期和时间匹配(约会日期)(约会时间) 如果它不存在,则将插入到数据库中 这是到目前为止我的代码。如何使SELECT的嵌套if语句更快、更简单 // Search for appointment by appointment

我需要交叉引用行。如果该行不存在,则插入该行

在将其插入数据库之前,需要通过以下标准:

首先查找属于该用户的约会(
user\u id

然后查找与约会ID匹配的约会(
appointment\u ID
)。如果约会ID不存在,请继续下一步

如果约会ID不存在,则搜索约会是否与约会日期和时间匹配(
约会日期
)(
约会时间

如果它不存在,则将
插入到数据库中

这是到目前为止我的代码。如何使
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...")
    }
}

如何使这个查询更快、更简单/更短?

我认为您可以尝试使用UNION来实现一个查询和一半代码

// 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) UNION (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_id', $appointmentId);
$stmt->bindParam(':appointment_date', $appointmentDate);
$stmt->bindParam(':appointment_time', $appointmentTime);
$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("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

如果尚未创建约会ID,您如何拥有它?@Devon约会ID来自另一个日历。我正在尝试使用Iodku同步两个日历Consider我确实需要先查看约会ID,然后再查看约会日期和时间OK,这样我就不知道你在问什么问题了。我只是在交叉引用我的日历和另一个日历。我正在尝试同步两个日历。在我的代码中,我试图在日历上搜索相同的约会/事件,从约会id开始,如果没有找到,则按日期和时间搜索。如果没有从中找到任何内容,那么事件将被插入,因为dbright中没有现有约会,但是如果需要分两步执行,那么您已经有了代码……那么您需要什么呢?我只是想知道是否有更快的方法来处理所有这些,特别是如果有100000多个约会