[英]MySQL query nested where condition
In my database, there are four types of individuals, youngOrc
, oldOrc
, youngHuman
, oldHuman
. 在我的数据库中,有四种类型的个人, youngOrc
, oldOrc
, youngHuman
, oldHuman
。
An individual belongs to a type conditional on a date range. 个人属于以日期范围为条件的类型。 Thus, I have tables like this for each type: 因此,对于每种类型,我都有这样的表:
youngOrcList ------------------- individual_id, start_date, end_date
This means that the guy with individual_id
is a youngOrc
between the start and end date. 这意味着,这个家伙individual_id
是youngOrc
的开始和结束日期之间。 He may be something else outside that range. 他可能不在这个范围内。 Similarly, I have a youngHuman
table. 同样,我有一张youngHuman
桌子。
Now, the real table of interest that I want to filter is events: 现在,我要过滤的真正感兴趣的表是事件:
events ------------------ source_individual_id target_individual_id event_date
Events table records all events between two individuals in my realm. 事件表记录了我领域中两个人之间的所有事件。 I want to filter so that I only select events
between youngOrc
and youngHuman
. 我想要过滤,以便只选择youngOrc
和youngHuman
之间的events
。
So this is a "nested" condition of sort, where I need both events.source_individual_id IN youngOrcList
AND events.event_date BETWEEN youngOrcList.start_date AND youngOrcList.end_date
. 因此,这是一个“嵌套”条件,在该条件下,我同时需要events.source_individual_id IN youngOrcList
和events.event_date BETWEEN youngOrcList.start_date AND youngOrcList.end_date
。 How to make this work? 如何使这项工作?
(Also, any suggestion regarding a better title would be great. I don't even know what to call this and thus unable to Google effectively.) (此外,关于更好的标题的任何建议都会很棒。我什至不知道该怎么称呼,因此无法有效地使用Google。)
This will give you all events between youngOrc and youngHuman: 这将为您提供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)
You can use join on tables. 您可以在表上使用联接。 They can be joined on a field individual_id
so then the only condition left for WHERE
clause will be the date condition: 他们可以在现场参加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
Alternatively, the WHERE
condition could be: 另外, WHERE
条件可以是:
WHERE e.event_date > MAX(o.start_date, h.start_date)
AND e.event_date < MIN(o.end_date, h.end_date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.