我看到有人使用语句来查询 MySQL 数据库中的表,如下所示:
select * from car_table where 1=1 and value="TOYOTA"
但1=1这里的意思是什么?
1=1
通常是在人们构建 SQL 语句的时候。
添加时,and value = "Toyota"您不必担心之前是否有条件或只是 WHERE。优化器应该忽略它
and value = "Toyota"
没有魔法,只有实用
示例代码:
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;