可能的重复: 为什么有人会在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是什么意思呢?
当前回答
当动态传递条件时,在复杂的查询中使用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 = "select * from car_table where 1=1"
for each condition in condition_set
sql = sql + " and " + condition.field + " = " + condition.value
end
这只是一个永远正确的表达。有些人把它作为一种变通方法。
它们有一个静态语句:
select * from car_table where 1=1
所以他们现在可以在where子句with中添加一些东西
and someother filter
1=1总是为真,所以value="TOYOTA"位是很重要的。
你可以在一些场景中得到这个,包括:
生成SQL:如果你不需要计算是否添加第一个条件,那么创建一个生成一个复杂的where语句会更容易,所以通常在开头放置1=1,所有其他条件都可以附加一个and
调试:有时你会看到人们在where条件的顶部放入1=1,因为它使他们能够在调试查询时自由地剪切和更改其余的条件。如。
select * from car_table
where 1=1
--and value="TOYOTA"
AND color="BLUE"
--AND wheels=4
不得不说,这不是特别好的实践,通常不应该出现在生产代码中。它甚至可能对查询的优化没有太大帮助。
通常是在人们建立SQL语句的时候。
当你加上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;
当动态传递条件时,在复杂的查询中使用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