Oct 29 2016 sql datetime whether two date range overlap 碰到一个需求,一个时间段内只允许有一个计划,也就是说数据库中的时间区间不能有重复或交叉,记录下从复杂到简单的简化过程。1.刚开始想的时候感觉这个有很多种情况,然后把每一次情况都用sql标识出来,写的语句如下。12345678910111213141516#情况如下:# a: |------|# b: |------|# a.start_time >= start_at and a.start_time <= end_at# a: |------| # b: |------|# a.end_time >= start_at and a.end_time <= end_at# a: |------|# b: |----------|# a.start_time >= start_at and a.end_time <= end_at# a: |----------|# b: |------|# a.start_time <= start_at and a.end_time >= end_at#代码如下:plan = Plan.where('((start_time >= ? and start_time <= ?) or (end_time >= ? and end_time <= ?) or (start_time >= ? and end_time <= ?) or (start_time <= ? and end_time >= ?) )',start_at, end_at, start_at, end_at, start_at, end_at, start_at, end_at) betweendatetimesql more >>