在PHP MySQL SELECT中嵌套if语句

时间:2018-09-06 19:36:05

标签: php mysql performance select pdo

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

在将其插入数据库之前,需要满足以下条件:

  

首先找到属于用户(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...")
    }
}

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

我认为您可以尝试使用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...")
}

我上面没有真正测试过此代码。可能需要一些调整。

告诉我如果事情太糟了。