BETWEEN和标准比较运算符Oracle SQL

时间:2017-07-12 04:58:33

标签: sql oracle between

由于我需要使用BETWEEN的数据范围,因为据我所知,以下两个查询应该相同:

select * from table1 where my_date1 - my_date2 between (-1) and (-30);

select * from table1 where my_date1 - my_date2 <= (-1) and my_date1 - my_date2 >= (-30);

然而,当我在我的剧本中尝试时:

SELECT  
       a.account_no AS ACCOUNT_NO, 
       a.installment_no AS INSTALLMENT_NO, 
       a.INSTALLMENT_DATE AS INSTALLMENT_DATE 
FROM myTable a 
     INNER JOIN (SELECT 
                        ACCOUNT_NO,
                        MIN(INSTALLMENT_NO) AS INSTALLMENT_NO 
                 FROM myTable  
                 WHERE 
                      ACCOUNT_NO IS NOT NULL 
                      AND INSTALLMENT_NO IS NOT NULL 
                      AND STATUS = 'A'
                      GROUP BY ACCOUNT_NO) b 
     ON A.ACCOUNT_NO = B.ACCOUNT_NO AND A.INSTALLMENT_NO = B.INSTALLMENT_NO
WHERE (TRUNC(INSTALLMENT_DATE) - TRUNC(TO_DATE('12/01/2011','DD/MM/YYYY'))) BETWEEN (-1) AND (-30) -- If I change this

我有0行,但是当我改变

WHERE (TRUNC(INSTALLMENT_DATE) - TRUNC(TO_DATE('12/01/2011','DD/MM/YYYY'))) BETWEEN (-1) AND (-30)

WHERE (TRUNC(INSTALLMENT_DATE) - TRUNC(TO_DATE('12/01/2011','DD/MM/YYYY'))) <= (-1) and (TRUNC(INSTALLMENT_DATE) - TRUNC(TO_DATE('12/01/2011','DD/MM/YYYY')))  >= (-30)

我获得超过0行。我想使用BETWEEN,因为它更具可读性。我错过了什么吗?

3 个答案:

答案 0 :(得分:2)

我相信BETWEEN使用范围的语法是:

WHERE col BETWEEN <smaller_value> AND <larger_value>

相当于

WHERE col >= <smaller_value> AND col <= <larger_value>

您当前的WHERE子句正在查找日期差异更大 <{1}}和更少而不是-1。这将消除您尝试定位的所有记录,实际上永远不会成为现实。要解决此问题,请更正范围:

-30

答案 1 :(得分:1)

https://docs.oracle.com/cd/B28359_01/server.111/b28286/conditions011.htm#SQLRF52147说:

  

expr1 [NOT] BETWEEN expr2 AND expr3

     

如果expr3&lt; expr2,则间隔为空。

答案 2 :(得分:1)

BETWEEN是一种语法快捷方式,评估为

WHERE col >= [smaller_value] AND <= [larger_value]

与VITAL相比,所比较的值按此顺序呈现(小而大),否则永远不会满足。

但是,我从不建议在日期范围之间使用,而是建议使用此语法代替:

WHERE col >= [smaller_value] AND < [larger_value]+1

此语法允许精确过滤任何时间精度级别的日期/时间信息。