我有一个表,其中包含一对表示时间跨度的时间戳。这些行由用户 ID 限定,每个用户可以有一个或多个与其关联的行。
该数据是从一个抽象的“可用性”表单生成的,该表单表示用户在一周内何时有空。我需要输入一系列时间范围作为查询并返回表中所有行都匹配的所有用户 ID。
鉴于此表:
CREATE TABLE "public"."availability" (
"id" int4 NOT NULL,
"user_id" int4,
"starts_at" timestamp(6),
"ends_at" timestamp(6),
PRIMARY KEY ("id")
) WITH (OIDS=FALSE)
这个数据:
User #1 is available Mon-Tue between 08:00 and 17:00
+----+---------+---------------------+---------------------+
| id | user_id | starts_at | ends_at |
+----+---------+---------------------+---------------------+
| 1 | 1 | 2013-03-18 08:00:00 | 2013-03-18 17:00:00 |
+----+---------+---------------------+---------------------+
| 2 | 1 | 2013-03-19 08:00:00 | 2013-03-19 17:00:00 |
+----+---------+---------------------+---------------------+
User #2 is available Sun-Sat all day
+----+---------+---------------------+---------------------+
| 3 | 2 | 2013-03-17 00:00:00 | 2013-03-23 23:59:59 |
+----+---------+---------------------+---------------------+
User #3 is available Wed between 06:00 and 18:00
+----+---------+---------------------+---------------------+
| 4 | 3 | 2013-03-20 06:00:00 | 2013-03-20 18:00:00 |
+----+---------+---------------------+---------------------+
我可以轻松地选择可用于任何给定时间戳的用户:
SELECT * FROM "public"."availability"
WHERE ('2013-03-19 08:35:00' BETWEEN starts_at AND ends_at
AND '2013-03-19 18:25:00' BETWEEN starts_at AND ends_at)
OR ('2013-03-20 12:00:00' BETWEEN starts_at AND ends_at
AND '2013-03-20 18:00:00' BETWEEN starts_at AND ends_at);
+----+---------+---------------------+---------------------+
| id | user_id | starts_at | ends_at |
+----+---------+---------------------+---------------------+
| 3 | 2 | 2013-03-17 00:00:00 | 2013-03-23 23:59:59 |
+----+---------+---------------------+---------------------+
| 4 | 3 | 2013-03-20 06:00:00 | 2013-03-20 18:00:00 |
+----+---------+---------------------+---------------------+
但我真正需要的是能够查询多个时间跨度并仅返回与所有条件user_id
匹配的 s 。
查询:2013-03-17 10:00:00
- 2013-03-17 16:00:00
,2013-03-23 10:00:00
-2013-03-23 16:00:00
应该返回:
+----+---------+---------------------+---------------------+
| id | user_id | starts_at | ends_at |
+----+---------+---------------------+---------------------+
| 3 | 2 | 2013-03-17 00:00:00 | 2013-03-23 23:59:59 |
+----+---------+---------------------+---------------------+
查询:2013-03-18 09:00:00
- 2013-03-18 16:00:00
,2013-03-19 08:00:00
-2013-03-19 15:45:00
应该返回:
+----+---------+---------------------+---------------------+
| id | user_id | starts_at | ends_at |
+----+---------+---------------------+---------------------+
| 1 | 1 | 2013-03-18 08:00:00 | 2013-03-18 17:00:00 |
+----+---------+---------------------+---------------------+
| 2 | 1 | 2013-03-19 08:00:00 | 2013-03-19 17:00:00 |
+----+---------+---------------------+---------------------+
| 3 | 2 | 2013-03-17 00:00:00 | 2013-03-23 23:59:59 |
+----+---------+---------------------+---------------------+
查询:2013-03-18 07:00:00
-2013-03-18 18:00:00
应该什么都不返回。