0

我正在使用Postgres數據庫構建應用程序,其中涉及比較計劃。我使用knex將它連接到節點;但如果解決方案最好由原始查詢提供,我也可以使用該路線。PostGres/Knex如何獲取兩個時間戳之間包含指定時間段的所有條目

我有一個名爲"Schedules"的表,它包含一個"from_time""to_time"

我希望能夠給予分貝"start_time""end_time",發現:

  1. ,可以包含"start_time"和「END_TIME」所有日程安排(即from_time <= start_time && end_time >= to_time
  2. 所有重疊的"start_time"時間表和"end_time"(即, (start_time <= from_time && end_time > from_time) || (start_time < to_time && end_time >= from_time))

的一種可能的解決方案,我認爲是簡單地storin g值作爲Unix時代的整數......這是我的備份計劃。但是,由於這些確實是時間值,因此最好將它們保留爲時間戳值格式。

+0

做'from_time'和'to_time'代表*時間戳*或*倍*?如果他們代表時間,是否有意義跨過00:00時間? (即:時間表從22:00開始,並於次日02:00結束)。 – joanolo

+0

當你得到結果時:你是否需要區分'overlapps'和'是否包含在'中(這只是'overlapps'的一個特例)? – joanolo

+0

看看http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=fbf5fe4c8b5611d92f87a7766f53cc4b,這是你在找什麼? – joanolo

回答

0

這一個是你的第一個條件

knex.select('*').from('Schedules').where('from_time', '<=', start_time).where('to_time', '<=', end_time) 

這一個是你的第二個

knex.select('*').from('Schedules').where(function() { 
    this.where('from_time', '>=', start_time).where('from_time' ,'<', end_time)) 
}).orWhere(function() { 
    this.where('to_time', '>', start_time).where('from_time' ,'<=', end_time)) 
}) 
相關問題