-- 最近经常看到有人在某段时间区间上喜欢用between ... and ... ,其实,可以直接地说:这种用法是错误的!
-- 查看某一天的数据,或某一段时间内的数据,其实是一个左闭、右开的区间内的数据;
-- 例如:我要查一张表 2011年3月11日到2011年3月24日内所生成的数据,其区间应该为[2011-03-11 00:00:00, 2011-03-25 00:00:00)
-- 即:不包括右边2011-03-25 00:00:00时间点的值!
-- 所以,请看如下:
create table t(cdate date);
insert into t(cdate) values(to_date('2011-03-23 00:00:00','yyyy-mm-dd hh24:mi:ss'));
insert into t(cdate) values(to_date('2011-03-23 11:09:25','yyyy-mm-dd hh24:mi:ss'));
insert into t(cdate) values(to_date('2011-03-24 00:00:00','yyyy-mm-dd hh24:mi:ss'));
insert into t(cdate) values(to_date('2011-03-24 02:03:45','yyyy-mm-dd hh24:mi:ss'));
insert into t(cdate) values(to_date('2011-03-24 10:37:03','yyyy-mm-dd hh24:mi:ss'));
insert into t(cdate) values(to_date('2011-03-24 20:55:17','yyyy-mm-dd hh24:mi:ss'));
insert into t(cdate) values(to_date('2011-03-24 23:59:59','yyyy-mm-dd hh24:mi:ss'));
insert into t(cdate) values(to_date('2011-03-25 00:00:00','yyyy-mm-dd hh24:mi:ss'));
insert into t(cdate) values(to_date('2011-03-25 01:44:22','yyyy-mm-dd hh24:mi:ss'));
-- 查看2011年24日生成的数据
-- 方法一:用 ... and ...
eygle@SZTYORA> select count(*) from t
2 where cdate>=to_date('2011-03-24','yyyy-mm-dd')
3 and cdate
COUNT(*)
----------
5
-- 方法二:用between ... and ...
eygle@SZTYORA> select count(*) from t
2 where cdate between to_date('2011-03-24','yyyy-mm-dd')
3 and to_date('2011-03-25','yyyy-mm-dd');
COUNT(*)
----------
6
eygle@SZTYORA> select * from t
2 where cdate between to_date('2011-03-24','yyyy-mm-dd')
3 and to_date('2011-03-25','yyyy-mm-dd')
4 order by cdate;
CDATE
-------------------
2011-03-24 00:00:00
2011-03-24 02:03:45
2011-03-24 10:37:03
2011-03-24 20:55:17
2011-03-24 23:59:59
2011-03-25 00:00:00
已选择6行。
-- 可见方法二用between ... and ... 是错误的,它将2011-03-25 00:00:00 这一时刻的记录也包括在内啦!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/12233.html