在我的数据库中,有四种类型的个人,youngOrc
,oldOrc
,youngHuman
,oldHuman
。
个人属于以日期范围为条件的类型。因此,我为每种类型都有这样的表格:
youngOrcList ------------------- individual_id, start_date, end_date
这意味着individual_id
的人在开始日期和结束日期之间是youngOrc
。他可能是该范围之外的其他东西。同样,我有一个youngHuman
表。
现在,我要过滤的真实感兴趣的表是事件:
events ------------------ source_individual_id target_individual_id event_date
事件表记录了我的领域中两个人之间的所有事件。我想过滤,以便我只在events
和youngOrc
之间选择youngHuman
。
所以这是排序的“嵌套”条件,我需要events.source_individual_id IN youngOrcList
和events.event_date BETWEEN youngOrcList.start_date AND youngOrcList.end_date
。如何使这项工作?
(另外,关于更好的标题的任何建议都会很棒。我甚至不知道该怎么称呼它,因此无法有效地使用Google。)
答案 0 :(得分:1)
这将为您提供youngOrc和youngHuman之间的所有活动:
SELECT *
FROM
Events e
WHERE EXISTS (
SELECT * FROM youngHumanList
WHERE individual_id IN (e.source_individual_id, e.target_individual_id)
AND e.event_date BETWEEN start_date AND end_date)
AND EXISTS (
SELECT * FROM youngOrcList
WHERE individual_id IN (e.source_individual_id, e.target_individual_id)
AND e.event_date BETWEEN start_date AND end_date)
答案 1 :(得分:0)
您可以在表格上使用联接。它们可以在字段individual_id
上连接,因此WHERE
子句唯一的条件是日期条件:
SELECT *
FROM youngOrcList AS o
JOIN events AS e ON e.source_individual_id = o.individual_id
JOIN youngHumanList AS h ON h.individual_id = e.target_individual_id
WHERE e.event_date BETWEEN o.start_date AND o.end_date
AND e.event_date BETWEEN h.start_date AND h.end_date
或者,WHERE
条件可以是:
WHERE e.event_date > MAX(o.start_date, h.start_date)
AND e.event_date < MIN(o.end_date, h.end_date)