当你添加and value = "Toyota"时,你不必担心在WHERE之前是否有条件。优化器应该忽略它
没有魔法,只是实用
示例代码:
commandText = "select * from car_table where 1=1";
if (modelYear <> 0) commandText += " and year="+modelYear
if (manufacturer <> "") commandText += " and value="+QuotedStr(manufacturer)
if (color <> "") commandText += " and color="+QuotedStr(color)
if (california) commandText += " and hasCatalytic=1"
否则你就得有一套复杂的逻辑:
commandText = "select * from car_table"
whereClause = "";
if (modelYear <> 0)
{
if (whereClause <> "")
whereClause = whereClause + " and ";
commandText += "year="+modelYear;
}
if (manufacturer <> "")
{
if (whereClause <> "")
whereClause = whereClause + " and ";
commandText += "value="+QuotedStr(manufacturer)
}
if (color <> "")
{
if (whereClause <> "")
whereClause = whereClause + " and ";
commandText += "color="+QuotedStr(color)
}
if (california)
{
if (whereClause <> "")
whereClause = whereClause + " and ";
commandText += "hasCatalytic=1"
}
if (whereClause <> "")
commandText = commandText + "WHERE "+whereClause;
the 1=1其中条件总是为真,因为总是1等于1,所以这个语句总是为真。
但有时它毫无意义。但其他时候,当where条件动态生成时,开发人员使用这个
例如,让我们看看这段代码
<?php
//not that this is just example
//do not use it like that in real environment because it security issue.
$cond = $_REQUEST['cond'];
if ($cond == "age"){
$wherecond = " age > 18";
}
$query = "select * from some_table where $wherecond";
?>
<?php
//not that this is just example
//do not use it like that in real environment because it security issue.
$cond = $_REQUEST['cond'];
if ($cond == "age"){
$wherecond = " age > 18";
} else {
$wherecond = " 1=1";
}
$query = "select * from some_table where $wherecond";
?>