我有一个通知表,有人可以在其中设置一周中的哪几天收到通知:
sun mon tue wed thu fri sat
现在我可以将它们创建为 bool 类型的单独列。
是否可以将这些存储在一个列中?
我需要像这样查询这些信息:
select * from notifications where start_date >= now and is_monday = true
制作一个不同的列会更明智还是某种整数/位掩码?不确定如何在数据库列中完成这是否是个好主意。
最佳答案
您可以创建枚举类型:
create type day_of_week as enum (
'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
);
并将其用作列类型,例如:
create table notifications (
id serial primary key,
event text,
start_date date,
day_of_week day_of_week
);
您的查询可能如下所示:
select *
from notifications
where start_date >= current_date
and day_of_week = 'mon'
请注意,类型的值是有序的,因此您可以,例如:
select *
from notifications
where day_of_week between 'mon' and 'thu'
使用函数 to_char()
从日期中获取 day_of_week
:
select to_char(current_date, 'dy')::day_of_week as dow
dow
-----
sun
(1 row)
更新。如果每个事件可能有更多通知,请使用 day_of_week
数组,示例:
create table notifications (
id serial primary key,
event text,
start_date date,
days_of_week day_of_week[]
);
insert into notifications values
(default, 'some event', '2018-10-01', '{mon, wed}');
select *
from notifications
where current_date >= start_date
and 'mon' = any(days_of_week);
关于sql - 将星期几存储在单个列中的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144745/