WHERE 子句中的括号是否为标准 sql
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16122695/
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
Are brackets in the WHERE clause standard sql
提问by whytheq
The course that I am currently doing uses brackets in its WHERE clauses like so:
我目前正在做的课程在其 WHERE 子句中使用括号,如下所示:
SELECT bar
FROM Foo
WHERE (CurrentState = 'happy');
Is this standard sql ?
If not then why use them?
这是标准的 sql 吗?
如果不是那么为什么要使用它们?
Doesn't seem to be used in the Date & Darwen book I have.
似乎没有在我拥有的 Date & Darwen 书中使用。
EDIT
编辑
Just to clarify - I'm referring to 1992 sql standards
只是为了澄清 - 我指的是 1992 sql 标准
回答by PaulProgrammer
Yes. You can use parenthesis to bind components of where clauses. This isn't necessary in your example, but if you had multiple and
and or
components, you might need parenthesis to either ensure correct order of operations or simply to self-document the query.
是的。您可以使用括号绑定 where 子句的组件。这在您的示例中不是必需的,但如果您有多个and
和or
组件,您可能需要括号来确保正确的操作顺序或只是为了自我记录查询。
Example 1:
示例 1:
select *
from foo
where
(class='A' and subclass='B')
or (class='C' and subclass='D')
In example 1, the parens aren't strictly required because and
binds more tightly than or
, but if you had multiple or
conditions tied by and
you would need it to get correct results, as in example 2 below.
在示例 1 中,括号不是严格要求的,因为and
绑定比 更紧密or
,但是如果您有多个or
条件被绑定,则and
需要它来获得正确的结果,如下面的示例 2 所示。
Example 2:
示例 2:
select *
from foo
where
(class='A' or class='B')
and (subclass='C' or subclass='D')
I use them in either case, because I don't like having to parse the sql in my head the same way the query optimizer does -- I'd rather be explicit about it and more quickly understand what the intent is.
我在任何一种情况下都使用它们,因为我不喜欢像查询优化器那样在我的脑海中解析 sql——我宁愿明确说明它并更快地理解意图是什么。
回答by Claudio Bredfeldt
They are optional. They make sense for more complex WHERE statements.
它们是可选的。它们适用于更复杂的 WHERE 语句。
... WHERE (created > '2012-10' AND created < '2013-01')
OR (modified > '2012-10' AND modified < '2013-01')
回答by John Woo
No. They are only required to be used when you have AND
on OR
conditions in your statement to avoid shortcircuits, just like this:
没有。他们只需要你的时候,必须使用AND
对OR
你的发言,以避免地短路的条件,就像这样:
SELECT...
FROM...
WHERE col1 > 1 AND col2 < 3 AND col3 >= OR col3 = 1 AND col5 < 1
The above query will give you unexpected result as it will not determine the correct condition it will take. A round brackets will help you segregate condition in this case,
上面的查询会给你意想不到的结果,因为它不会确定它将采用的正确条件。在这种情况下,圆括号将帮助您隔离条件,
SELECT...
FROM...
WHERE col1 > 1 AND col2 < 3 AND (col3 >= OR col3 = 1) AND col5 < 1
by the way, it should be single quotes ' '
not ‘ '
顺便说一句,它应该是单引号' '
而不是‘ '