10

我正在处理一些我正在维护的查询,并且一个程序员向我输入了“1 = 1”的查询,这似乎总是评估为真。

这有好处吗?

重复: 为什么有人会在 SQL 子句中使用 WHERE 1=1 AND?

这个问题不是这个问题的答案。

Where-子句:

select * from table where 1=1 and sStatus not in ('status1','status2','status3')

无需编程或 if 语句将 and 推入其中。直接查询。

如果您可以取消关闭它,我想知道是否有目的,以便我可以重写并删除 1=1 如果没有必要。

4

7 回答 7

19

是动态查询吗?有时这在基于可选参数构建动态查询时很有帮助。

于 2009-02-05T18:09:17.273 回答
16

If you automatically want to add restrictions to your query, it makes your life easier:

string sql = "SELECT * FROM table WHERE 1=1";

if (someflag) {
  sql += " AND valid = 1";
}

if (someotherflag) {
  sql += " AND special = 1";
}

execute(sql);

Without WHERE 1 = 1 you would in each case have to check if it's the first restriction you add (and then use WHERE ...) or if you already added some other restriction before (and then add AND ...).

于 2009-02-05T18:15:14.360 回答
12

如果您正在动态构建 where 子句,您可能会有点懒惰并假设您添加的每个子句都可以以“AND”为前缀,例如

$str="select foo from bar where 1=1";

if ($filter1)
{
    $str.=" and col1='frobozz'";
}
于 2009-02-05T18:13:45.313 回答
6

当我在做一些惰性编程时,我将它用于动态 where 子句,并且不想总是检查子句是否为空以确定我现在是否需要在动态子句之间使用“AND”。

于 2009-02-05T18:12:45.270 回答
4

这仅在动态查询中才有意义。如果您在循环中添加参数,而不必检查是否已经存在 WHERE,您可以每次都附加 AND Column = Value。

于 2009-02-05T18:13:08.450 回答
1

我已经看到了两个原因,当你总是想要一个真实的结果,或者当语句中附加任意数量的“and condition = value”时

于 2009-02-05T18:10:42.760 回答
0

That is very interesting... The WHERE clause contains nothing but 1=1? I have seen this frequently in SQL injection attempts in which the WHERE clause is set to xyz="something" OR 1=1; as a means to always return a list of results.

Can you tell us more about what is going on with this query so we might be able to answer the question better?

  • Nicholas
于 2009-02-05T18:13:47.793 回答