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)
给出一个时间段,判断是否和数据库已存在的时间区间有重叠的部分 补充:
# 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 >= :start_at and start_time <= :end_at) or (end_time >= :start_at and end_time <= :end_at) or (start_time >= :start_at and end_time <= :end_at) or (start_time <= :start_at and end_time >= :end_at) )',start_at: start_at, end_at: end_at)
优化后的结果:
# a: |------|
# b: |------|
# a.start_time >= start_at and a.start_time <= end_at
# a: |------|
# b: |------|
# a.start_time <= start_at and a.end_time >= start_at
plan = Plan.where('((start_time >= :start_at and start_time <= :end_at) or (start_time <= :start_at and end_time >= :start_at) )',start_at: start_at, end_at: end_at)
#12 楼 最终的结果:
plan = Plan.where('start_time <= ? and end_time >= ?', end_at, start_at)