簡體   English   中英

SQL從表列值中選擇子查詢IN

[英]SQL select subquery IN from table column values

首先,對可能無法正確表達問題的標題表示歉意,我對SQL查詢不是很滿意。

我有一個表“停車場”,像這樣的列

| days_2        | from_hr   | to_hr
"1,2,3,4,5"     "08:00:00"  "18:00:00"
"0,1,2,3,4,5,6" "08:00:00"  "22:00:00"
...
...

我做了下一個查詢,它工作正常:

SELECT Extract(dow from current_timestamp::DATE) as Day, 
    current_time BETWEEN from_hr and to_hr as ParkHour, 
    days_2, 
    from_hr, 
    to_hr  
FROM public.parkings;

如果今天是星期一,當前時間是21:26:00,則結果為:

day | ParkHour  | days_2        | from_hr   | to_hr
1    f          "1,2,3,4,5"     "08:00:00"  "18:00:00"
1    t          "0,1,2,3,4,5,6" "08:00:00"  "22:00:00"
...
...

我想以如下方式修改此查詢:如果當前天數在該記錄的表列days_2中,則在第一列中將存儲結果(是/ 否) ,方式是這樣的

SELECT Extract(dow from current_timestamp::DATE)  in (1,2,3,4,5,6);

例如,如果現在是星期天(0),則第一行的最終結果為false,而第二行的結果為true:

day | ParkHour  | days_2        | from_hr   | to_hr
 f   f          "1,2,3,4,5"     "08:00:00"  "18:00:00"
 t   t          "0,1,2,3,4,5,6"  "08:00:00" "22:00:00"

我怎樣才能做到這一點?

謝謝!

select
    extract(dow from now())
    =
    any (regexp_split_to_array('1,2,3', ',')::integer[]);
 ?column? 
----------
 t

將該列類型轉換為數組將避免字符串拆分步驟。

http://www.postgresql.org/docs/current/static/arrays.html

嘗試

select 
  case
    when Extract(dow from current_timestamp::DATE) = '0' then 't' else 'f'
    when Extract(dow from current_timestamp::DATE) = '1' then 't' else 'f'
    when Extract(dow from current_timestamp::DATE) = '2' then 't' else 'f'
    when Extract(dow from current_timestamp::DATE) = '3' then 't' else 'f'
    when Extract(dow from current_timestamp::DATE) = '4' then 't' else 'f'
    when Extract(dow from current_timestamp::DATE) = '5' then 't' else 'f'
    when Extract(dow from current_timestamp::DATE) = '6' then 't' else 'f'
  end as day,
  current_time BETWEEN from_hr and to_hr as ParkHour, 
  days_2, 
  from_hr, 
  to_hr  
from public.parkings;

正如其他人提到的那樣,如果您的表結構更好和/或使用數組,會更容易。

高溫超導

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM