繁体   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