在没有运气的情况下搜索高低,找到一个有效的SQL,允许我根据不在给定日期范围内的日期在另一个表中查找丢失的记录。
表:订阅
+------------+
| id | label |
+------------+
| 1 | aaa |
+------------+
| 2 | bbb |
+------------+
| 3 | ccc |
+------------+
| 4 | ddd |
+------------+
表: subscription_periods
+------------------------------------------------+
| id | subscription_id | start_at | end_at |
+------------------------------------------------+
| 1 | 1 | 2015-12-01 | 2016-01-01 |
+------------------------------------------------+
| 2 | 1 | 2016-01-01 | 2016-02-01 |
+------------------------------------------------+
| 3 | 2 | 2015-12-01 | 2016-01-01 |
+------------------------------------------------+
| 4 | 3 | 2016-02-01 | 2016-03-01 |
+------------------------------------------------+
目标:说,今天 2016-01-15 ,我想找到subscriptions
的记录,这些记录缺少今天没有覆盖的subscription_periods
记录在给定的日期范围内(subscription_periods.start_at
和subscription_periods.end_at
)。
根据以上数据,subscriptions.id #2, #3 and #4
根据给定的日期范围没有涵盖 2016-01-15 的subscription_periods
记录,因此预期结果会显示像这样:
+------------+
| id | label |
+------------+
| 2 | bbb |
+------------+
| 3 | ccc |
+------------+
| 4 | ddd |
+------------+
任何提示都会受到高度赞赏,任何遇到这个问题的人也会非常感激。
答案 0 :(得分:2)
此查询将返回特定日期的subscription_periods中缺少的订阅
SELECT DISTINCT S.id, S.label
FROM subscriptions AS S
LEFT JOIN subscription_periods AS SP
ON S.id = SP.subscriptions_id AND @yourDateHere BETWEEN start_at AND end_at
WHERE SP.id IS NULL