[英]Nested if statement in PHP MySQL SELECT
我需要交叉引用行。 如果該行不存在,則將其插入。
在將其插入數據庫之前,需要遵循以下條件:
首先找到屬於該用戶的約會(
user_id
)。然后找到與約會ID(
appointment_id
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...")
}
}
我怎樣才能使它更快,更簡單/更短?
如果您不需要區分兩個查詢,則只需組合您的條件即可:
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
我認為您可以嘗試使用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...")
}
我沒有在上面真正測試過此代碼。 它可能需要一些調整。
告訴我是否有什么問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.