[英]Join itself where parent date between child dates
我正在努力構建一個查詢,該查詢將通過ID從表中獲取一些行,然后從同一表中連接行,其中start_date
和end_date
在父start_date
之間。 考慮表像
事件
| id | event_type_id | start_date | end_date |
| 1 | 1 | 10 | 100 |
| 2 | 2 | 5 | 20 |
| 3 | 2 | 8 | 50 |
event_type_id
= 1的事件類似於普通事件,而= 2的事件是周期事件。 我想建立查詢,以便獲得所有正常事件,但同時還有start_date
和end_date
在正常事件start_date
之間的期間事件。 因此,考慮上面的示例,我想獲取id
為1的事件,並加入event_type_id
為2的事件,且start_date
和end_date
在10之間。請注意,即使只有1條event_type_id
= 1的記錄,也會有更多的記錄,我想將所有這些都放在一個查詢中。 我知道單條記錄很容易做到,但是我想像一棵整棵樹一樣取,所以我不會以n + 1結尾。 甚至有可能還是我應該考慮其他方法?
SELECT
e1.*,
e2.*
FROM
events e1 LEFT JOIN events e2
ON
e1.start_date BETWEEN e2.start_date AND e2.end_date
AND
e2.event_type_id=2
WHERE
e1.event_type_id=1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.