gpt4 book ai didi

mysql - "where 1=1"声明

转载 作者:IT老高 更新时间:2023-10-28 12:48:43 24 4
gpt4 key购买 nike

Possible Duplicate:
Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

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

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

但是这里的 1=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;

关于mysql - "where 1=1"声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8149142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com