Possible Duplicate:
为什么有人在SQL子句中使用1 = 1和<条件>?
我看到有些人使用语句在MySQL数据库中查询表:如下:
select * from car_table where 1=1 and value="TOYOTA"
但是有什么1=1
刻薄在这里?
答案
通常是人们建立SQL语句的时候。
当您添加时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;