8

SQL Server 上的 BETWEEN 查询中 v1 和 v2 的顺序是否存在差异?

SELECT *
  FROM table
 WHERE col BETWEEN v1 AND v2

如果 v1 大于 v2,目前我没有得到任何结果。这是唯一的语法糖吗

col >= v1 AND col <= v2

还是真的需要两者之间的所有值?根据我目前的观察,我想这是第一种情况。

4

3 回答 3

13

SQL Server 2008:

select 1 
where 5 between 1 and 7

1 个结果

select 1 
where 5 between 7 and 1

0 个结果

基于这些结果和Postgre 文档 ,我假设 ANSI 标准如下(尽管我找不到该文档)。

a between x and y
==
a >= x AND a <= y

更新:

SQL-92 规范说(引用):

"X BETWEEN Y AND Z" is equivalent to "X>=Y AND X<=Z"
于 2009-10-15T14:46:05.240 回答
11

是的!BETWEEN 谓词中的参数顺序。而且,是的,这 [大部分] 是 AND 比较形式的语法糖。

The "mostly", above comes from the fact that while logically equivalent, the two expressions may (probably in the past...) receive a distinct query plan on some SQL servers. It is a safe guess that most servers, nowadays, provide an optimal handling of this type of filter, regardless of its form.

于 2009-10-15T14:46:35.040 回答
4

Yes, you are right, is it only syntactic sugar for the construct you mentioned.

于 2009-10-15T14:47:48.123 回答