Postgresql

如何確定一個表中的時間戳是否在另一個表的子查詢中的兩個時間戳之間?

  • January 27, 2017

我有兩張表——一張名為“index”,其中包含帶有時區的“datetime”時間戳,一張名為“planning”,其中包含“start_time”和“end_time”時間戳。

這是兩個表的架構(為便於閱讀而編輯):

                Table "public.index"
   Column     |           Type           | Modifiers 
---------------+--------------------------+-----------
datetime      | timestamp with time zone | not null
pln           | boolean                  | 

                    Table "public.planning"
     Column      |           Type           |         Modifiers          
------------------+--------------------------+----------------------------
name             | text                     | 
start_time       | timestamp with time zone | 
end_time         | timestamp with time zone | 
macro            | text                     | 
state            | text                     | default 'deselected'::text

TRUE如果它們的“日期時間”時間戳介於“計劃”表的子查詢中的“開始時間”和“結束時間”之間,我想分配給“索引”表中的項目。這是我的嘗試:

UPDATE index 
SET pln=TRUE
WHERE datetime BETWEEN (SELECT start_time 
                       FROM planning 
                       WHERE state='selected' AND macro NOT LIKE 'mae%')
                  AND (SELECT end_time 
                       FROM planning 
                       WHERE state='selected' AND macro NOT LIKE 'mae%');

這導致錯誤:

ERROR:  more than one row returned by a subquery used as an expression

您可以使用一個EXISTS子查詢來做到這一點:

UPDATE "index" AS i 
SET pln = TRUE
WHERE EXISTS 
     ( SELECT *
       FROM planning AS p
       WHERE p.state = 'selected' 
         AND p.macro NOT LIKE 'mae%'
         AND p.start_time <= i.datetime 
         AND i.datetime < p.end_time 
     ) ;

我更改了BETWEENto>= start_time< end_time,因為它更常見(也更明智)具有包含獨占的日期時間範圍。您可以將其更改回>=and<=或 to (等價物) BETWEEN

引用自:https://dba.stackexchange.com/questions/162378