【发布时间】:2015-10-23 14:21:22
【问题描述】:
我有一个 postgres 表,用于存储名为 appointments 的定期约会。我还有一个名为day_of_week 的枚举类型。
day_of_week 是一个看起来像这样的枚举:
select enum_range(null::ck_day_of_week);
返回
{Monday,Tuesday,Thursday,Sunday,Saturday,Friday,Wednesday}
约会表的 DDL 是:
create table appointments
(
id serial primary key not null,
title varchar not null
recurrence_start_date timestampz not null,
recurrence_end_date timestampz,
recurrence_days_of_week _ck_day_of_week -- this is actually an array of enums, not just an enum. I don't fully understand why the DDL looks like this
);
一个查询
select id, title, recurrence_days_of_week from appointments where recurrence_start_date <= now() and (recurrence_end_date is null or recurrence_end_date >= now());
返回如下内容:
1,My Recurring Appointment,{Wednesday,Thursday,Friday,Saturday,Sunday}
我的问题是,我需要将此结果“具体化”为 UI 视图的一组行。具体来说,我想查询数据库并让它返回如下行:
id,My Recurring Appointment,date
其中唯一键可能是约会 ID 和特定 date,而 date 本质上是recurrence_start_date + 星期几的组合(星期几是0 到6 之间的偏移量)。
在 postgres 中,如何从具有枚举数组列的表中进行选择,并让它为数组中的每个枚举值返回 --real-- 同一行的 --virtual- 单行?我正在考虑一个视图或其他东西,但我现在确定如何编写 select 语句。
如果这可以翻译成 SQLAlchemy 加分....
我也打开并考虑创建一个约会表来存储每个约会及其特定日期。但如果我这样做......理论上,对于没有结束日期的重复日期的约会,表格可能会无限大,所以我一直在努力避免这种情况。
【问题讨论】:
标签: python postgresql sqlalchemy