sql - 将星期几存储在单个列中的最佳方式

标签 sql postgresql dayofweek

我有一个通知表,有人可以在其中设置一周中的哪几天收到通知:

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/

相关文章:

sql - 设置 NOCOUNT OFF 或返回 @@ROWCOUNT?

SQL 将 B 列中与 A 列中具有相同值的所有值连接到 A 列中的所有值

django - Apache 用户对 PostgreSQL 数据库的权限

Python:在 isocalendar 或 strftime 或其他中定义周定义中的起始日

java - 如何从 Instant.now() 获取 DayOfWeek

mysql - 将返回重复彩票号码的 SQL 查询

Java错误: Cannot convert void to double

sql - 存储多种数据类型

sql - 在我的案例中如何比较表中的记录?

sql - 简单的 SQL 查询 : need this month data and previous month last 5 days data together