在 Oracle 中,使用 1=1 启动 SQL 查询的 WHERE 子句有用吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1069373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Oracle, is starting the SQL Query's WHERE clause with 1=1 useful?
提问by Blanthor
I'm working with a client that starts almost all of their WHERE clauses in Oracle with 1=1
. Forgive my ignorance, but isn't this a no-op? Are there any negative consequences of this usage?
我正在与一个客户合作,该客户在 Oracle 中几乎所有的 WHERE 子句都使用1=1
. 原谅我的无知,但这不是空运吗?这种用法有什么负面影响吗?
Here's a scrubbed example:
这是一个擦洗的示例:
SELECT gpz.zname
,gpp.pname
FROM table1 gpp INNER JOIN table2 gpz ON gpz.p_id = gpp.p_id
WHERE 1=1
AND gpp.active = 1
AND gpz.active = 1
回答by cletus
It's done to simplify dynamic SQL generation. Basically each condition can be added as AND <condition>
without treating the first condition as special (it's preceded by WHERE
not AND
) or even worrying if there should be a WHERE
clause at all.
这样做是为了简化动态 SQL 生成。基本上每个条件都可以添加,AND <condition>
而不会将第一个条件视为特殊条件(它前面是WHERE
not AND
),甚至不必担心是否应该有一个WHERE
子句。
So just write it off as easy of use or, arguably, laziness.
因此,只需将其写为易于使用,或者可以说是懒惰。
回答by Jim Hudson
If they are building the query dynamically, you should check whether they're using bind variables. Building the query from literals requires extra parsing, potentially limiting scalability, and also can greatly increase the risk of SQL Injection attacks.
如果他们动态构建查询,您应该检查他们是否使用绑定变量。从文字构建查询需要额外的解析,这可能会限制可扩展性,并且还会大大增加 SQL 注入攻击的风险。
where 1 = 1 and my_id = :b1;
(and then defining the value of the bind variable)
(然后定义绑定变量的值)
is generally much better than:
通常比:
where 1 = 1 and my_id = 123456;
回答by John Barrett
They may have built the query from substrings.
他们可能已经从子字符串构建了查询。
It may be a way to build it with just AND
s, depending on the business rule match, so you don't really have to care which is your first condition.
这可能是一种仅使用AND
s构建它的方法,具体取决于业务规则匹配,因此您不必真正关心哪个是您的第一个条件。
Wouldn't do it that way myself.
我自己不会那样做。