简体   繁体   中英

MySQL query nested where condition

In my database, there are four types of individuals, 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. He may be something else outside that range. Similarly, I have a youngHuman table.

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 .

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 . 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.)

This will give you all events between youngOrc and 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:

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 e.event_date > MAX(o.start_date, h.start_date)
AND e.event_date < MIN(o.end_date, h.end_date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM