GaussDB between的用法

1 between的作用

between 操作符用于选取介于两个值之间的数据范围内的值。

2 between的边界

betweenN运算符选择给定范围内的值。值可以是数字,文本或日期。

between运算符是包含性的:包括开始和结束值,等价于>= AND <=

3 between的语法

SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2;

4 示例数据库

复制代码
以下是"Products"表中的数据:

create table products(
    id int not null,
    name varchar(20) null,
    supplier_id int null,
    catalog_id int null,
    specification varchar(50) null,
    price numeric(18, 2) null
);

insert into products (id,name,supplier_id,catalog_id,specification,price)
values
( 1, '面包', 1, 1, '10个/袋', 18.00 ), 
( 2, '大米', 1, 1, '25kg/袋', 75.00 ), 
( 3, '苹果', 1, 2, '10kg/箱', 50.00 ), 
( 4, '香蕉', 2, 2, '10kg/箱', 45.00 ), 
( 5, '雪梨', 2, 2, '10kg/箱', 60.00 );

5 between 使用举例

以下sql语句选择价格在30到60之间的所有产品:

复制代码
select * from products where price between 30 and 60;

结果:

可以看到 价格 那一列的数据都是介于30(包含)和60(包含)之间的

6 not between 实例

要显示前面示例范围之外的产品,请使用not between:

复制代码
select * from products where price not between 30 and 60; 
或 
select * from products where not price between 30 and 60;

结果:

7 带有 in 的 between 操作符实例

以下SQL语句选择价格在10到60之间但名称不是大米和香蕉的所有产品:

复制代码
select * from products where (price between 10 and 60) and name not in ('大米','香蕉');

因为大米和香蕉都是字符类型,所以要用单引号('')
结果:

可以看到价格一列均满足10 到 60 之间,名称一列香蕉 ( 的价格本来也符合,但是因为我们用 not in 把他排除了,所以也不显示出来。

8 带有文本值的 BETWEEN 操作符举例

以下SQL语句选择所有带有名称 BETWEEN'面包'和'香蕉'的产品:

复制代码
select * from products where name between '面包' and '香蕉';

结果:

9 带有日期值的 BETWEEN 操作符举例

以下 SQL 语句选取 订单日期 介于 '2018-06-28' 和 '2018-09-28' 之间的所有订单:

复制代码
select * from orders where order_date between timestamp '2018-06-28 00:00:00' and  timestamp '2018-09-28 00:00:00';

结果:

注:

between and在处理日期可能会有你意向不到的结果,SQL中 between and是包括边界值的,not between不包括边界值,不过如果使用between and 限定日期需要注意,如果and后的日期是到天的,那么默认为00:00:00 例如:and 后的日期为2018年09月28日,就等价于2018-09-28 00:00:00 ,那么2018-09-28 11:24:54.000的数据就查不到了,如果要查到2018-09-28这一整天的数据,那么在取值的时候需要加1天,即between '2018-06-28' AND '2018-09-29',这样返回的就是6月28日(含)到9月28日(含)的所有数据了。