可能的重复: 为什么有人会在SQL子句中使用WHERE 1=1 AND <条件> ?
我看到一些人使用语句来查询MySQL数据库中的表,如下所示:
select * from car_table where 1=1 and value="TOYOTA"
但是这里1=1是什么意思呢?
可能的重复: 为什么有人会在SQL子句中使用WHERE 1=1 AND <条件> ?
我看到一些人使用语句来查询MySQL数据库中的表,如下所示:
select * from car_table where 1=1 and value="TOYOTA"
但是这里1=1是什么意思呢?
当前回答
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";
?>
因此,在上面的例子中,如果$_REQUEST['cond']不是"age",查询将返回mysql错误,因为在where条件之后什么都没有。
查询将被select * from some_table 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";
} else {
$wherecond = " 1=1";
}
$query = "select * from some_table where $wherecond";
?>
所以现在如果$_REQUEST['cond']没有age, $wherecond将是1=1,所以查询将不会有mysql错误返回。
查询将select * from some_table where 1=1,避免mysql错误
希望你能理解我们使用1=1,同时注意上面的例子不是真实世界的例子,它只是向你展示这个想法。
其他回答
当我需要动态应用过滤器时,我就这样做了。 比如,在编码时,我不知道有多少过滤器用户将应用(fld1 = val1和fld2=val2和…) 因此,为了重复语句“and FLD = val”,我从“1 = 1”开始。 因此,我不需要修饰语句中的第一个“和”。
该查询查找1 = 1且value = 'TOYOTA'的所有行。因此,在这种情况下,它是无用的,但如果您省略了WHERE语句,使用WHERE 1=1来提醒您选择不使用WHERE子句可能是一个好主意。
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";
?>
因此,在上面的例子中,如果$_REQUEST['cond']不是"age",查询将返回mysql错误,因为在where条件之后什么都没有。
查询将被select * from some_table 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";
} else {
$wherecond = " 1=1";
}
$query = "select * from some_table where $wherecond";
?>
所以现在如果$_REQUEST['cond']没有age, $wherecond将是1=1,所以查询将不会有mysql错误返回。
查询将select * from some_table where 1=1,避免mysql错误
希望你能理解我们使用1=1,同时注意上面的例子不是真实世界的例子,它只是向你展示这个想法。
当动态传递条件时,在复杂的查询中使用this,你可以使用“AND”字符串连接条件。然后,不计算传入的条件的数量,而是在stock SQL语句的末尾放置“WHERE 1=1”,并抛出连接的条件。
不需要用1=1你可以用0=0 2=2,3=3,5=5 25=25 ......
select * from car_table where 0=0 and value="TOYOTA"
这里你也会得到相同的结果,就像1=1的条件
因为所有这些情况都是真实的表达
1=1 is alias for true
大多数时候,如果开发人员正在开发查询构建器类型的应用程序或构建一些复杂的SQL查询,则使用这些类型的查询,因此在选择语句字符串中添加一个条件子句Where 1=1,并且在程序中不需要为它添加任何检查。