简体   繁体   English

MySQL SELECT 多条件

[英]MySQL SELECT with multiple conditions

When searching for available cars, I'm trying to SELECT from cars table WHERE the IDs do not include the already booked cars.在搜索可用汽车时,我正在尝试从汽车表中WHERE SELECT ,其中 ID 不包括已预订的汽车。 For that, I used:为此,我使用了:

$result = $pdo->prepare("SELECT * FROM cars 
WHERE id NOT IN (" . implode(',', $bookedCarIds) . ") 
AND (location = '$fromlocation'  AND fromdate BETWEEN '$fromdate' AND '$todate') 
"); 

$result->execute();
$availableCars = [];
$availableCars = $result->fetchAll();

Which works perfectly fine.效果很好。

However, the issue arises when there are no already booked cars in the selected location and dates (where $bookedCarsIds is NULL ).但是,当所选位置和日期(其中$bookedCarsIdsNULL )中没有已预订的汽车时,就会出现问题。 To deal with this issue, I used the following code, which throws a syntax error.为了处理这个问题,我使用了下面的代码,它会抛出一个语法错误。

$result = $pdo->prepare("SELECT * FROM cars 
WHERE id NOT IN (" . implode(',', $bookedCarIds) . ") AND 
(location = '$fromlocation'  AND fromdate BETWEEN '$fromdate' AND '$todate') 
OR WHERE location = '$fromlocation'  AND fromdate BETWEEN '$fromdate' AND '$todate'
");

 $result->execute();
 $availableCars = [];
 $availableCars = $result->fetchAll();

How can I solve this issue by making changes in this MySQL query alone, without altering the rest of my code?如何通过仅在此 MySQL 查询中进行更改而不更改我的代码的 rest 来解决此问题?

Thank you.谢谢你。

If you are using PDO , you need to create a dynamic WHERE clause with parameters like in this example:如果您使用的是PDO ,则需要使用以下示例中的参数创建一个动态WHERE子句:

$whereClause = [];
$params = [];
if (!empty($bookedCarIds)) {
    $whereClause[] = 'id NOT IN (?' . str_repeat(', ?', count($bookedCarIds) - 1) . ')';
    $params = $bookedCarIds;
}
if (!empty($fromlocation)) {
    $whereClause[] = 'location = ?';
    $params[] = $fromlocation;
}
if (!empty($fromdate) && !empty($todate)) {
    $whereClause[] = 'fromdate BETWEEN ? AND ?';
    $params[] = $fromdate;
    $params[] = $todate;
}
$whereClause = !empty($whereClause) ? 'WHERE ' . implode(' AND ', $whereClause) : '';

$result = $pdo->prepare("SELECT * FROM cars $whereClause");
$result->execute($params);
$availableCars = $result->fetchAll();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM