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