如何在SQL命令中使用两个where语句?

时间:2014-03-20 13:14:06

标签: php mysql

我有一些代码可以在两个日期之间选择数据库中的所有条目,但我也希望它不会在“状态”列中选择“删除”。我可以让它做任何一次,但不能同时做到。

try {
$DBH = new PDO("mysql:host=localhost;dbname=$dbname",$dbuser,$dbpass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->prepare("SELECT Link, Type, Location, Urgency, Date, Time, Status, Days FROM reports WHERE truedate BETWEEN :start_date AND :end_date");
$STH->execute(array(':start_date' => $start_date_variable, ':end_date' => $end_date_variable));


$rows = $STH->fetchAll(PDO::FETCH_ASSOC);

echo "<table>";

foreach ($rows as $row) {
    echo "<tr><td>" . $row['Link'] . "</td><td>" . $row['Type'] . "</td><td>" . $row['Location'] . "</td><td>" . $row['Urgency'] . "</td><td>" . $row['Date'] . "</td><td>" . $row['Time'] . "</td><td>" . $row['Status'] . "</td><td>" . $row['Days'] . "</td></tr>";
}

echo "</table>";

}catch(PDOException $e) {
echo $e->getMessage();
}

那么如何使用两个where语句来缩小搜索范围?

2 个答案:

答案 0 :(得分:3)

AND检查之前,只需使用truedate运算符,如图所示。

SELECT Link, Type, Location, Urgency, Date, Time, Status, Days FROM reports WHERE Status NOT LIKE '%Removed%' AND truedate BETWEEN :start_date AND :end_date

答案 1 :(得分:1)

尝试使用以下

更新您的代码
$STH = $DBH->prepare("SELECT Link, Type, Location, Urgency, Date, Time, Status, Days FROM reports WHERE Status != :statusval AND truedate BETWEEN :start_date AND :end_date");
$STH->execute(array(':statusval ' => 'Removed', ':start_date' => $start_date_variable, ':end_date' => $end_date_variable));