小编典典

“其中 1 = 1”语句

all

我看到有人使用语句来查询 MySQL 数据库中的表,如下所示:

select * from car_table where 1=1 and value="TOYOTA"

1=1这里的意思是什么?


阅读 69

收藏
2022-06-25

共1个答案

小编典典

通常是在人们构建 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;
2022-06-25