PostgreSql/lightdb中有两个非常方便、有用的比较操作,OVERLAPS 和 BETWEEN SYMMETRIC。
1. OVERLAPS(重叠)
OVERLAPS操作,用于检测两个日期范围是否重叠。举例:
SELECT (DATE '2020-11-10', DATE '2020-12-01') OVERLAPS (DATE '2020-11-20', DATE '2020-12-11');
1
结果返回true。
时间范围边界有两种方式:
日期(times or timestamps),与上面示例一样
date 和 interval,见下面示例。
SELECT (DATE '2020-11-10', INTERVAL '1 month') OVERLAPS (DATE '2016-12-11', INTERVAL '7 days');
1
结果返回true。
注意:如果第一个时间范围的截至时间等于第二个时间范围的开始时间,结果返回false。
2. BETWEEN SYMMETRIC
我们都用过 value BETWEEN X AND Y,其实就是 value >= X AND value <= Y。举例:
SELECT * FROM users WHERE id BETWEEN 2 AND 4
1
则返回id为2,3,4的用户信息。
value BETWEEN X AND Y 是假设x 比 y 小,否则查询结果为空。举例:
SELECT * FROM users WHERE id BETWEEN 4 AND 2
1
实际应用中x , y可能是用户传入的参数,有可能没有按照约定传入,导致查询结果为空。BETWEEN SYMMETRIC 可以解决该问题。
下面通过示例说明:
> select * from generate_series(1,10) as numbers(a)
where numbers.a between 3 and 6;
a
---
3
4
5
6
如果between参数颠倒,返回结果为空:
> select * from generate_series(1,10) as numbers(a)
where numbers.a between 6 and 3;
a
请出between symmetric:
> select * from generate_series(1,10) as numbers(a)
where numbers.a between symmetric 6 and 3;
a
---
3
4
5
6
参数顺序不重要了。
标签:OVERLAPS,postgresql,between,SYMMETRIC,numbers,BETWEEN,DATE From: https://www.cnblogs.com/lightdb/p/17026691.html