简体   繁体   中英

MySQL sub-query AND 'NOT IN'

sorry if this has been answered before; I'm a little unsure how best to describe this problem never mind search for it. But here goes...

Basically I have a 'projects' table, which holds and 'id' and a 'title'. I also have a 'projects_history' table which holds information when (IF) the project is set to archived (a boolean value). It has a 'pid' key that references the project - there can be more than one record for each project as it is updated (in order to track who sets the value to what).

There's also a 'project_enquiries' table that holds information on enquiries that have been raised for the project, so there is a 'pid' key that references 'projects'. Similarly, there's a 'project_enquiry_history' table that records when (IF) the enquiry is set to closed (a boolean value). It has a 'eid' key that references the project_enquiry - there can be more than one record for each enquiry as it is updated (in order to track who sets the value to what).

My query aims to pull out the projects that haven't been archived (so either there is no record in 'project_history' or the most recent record for the project has 'archived' = 0), which have enquiries that are still open (so either there is no record in 'project_enquiry_history' or the most recent record for the enquiry has 'open' = 1).

I'm really struggling on where to start with the query.

The first thing is that if there is no record in project_history , then you will need to do a left join of your projects table on the project_history table using your project id to discover this. You will have entries in the results that are null in the columns for project_history where there is no corresponding entry. You can then chain that process, using the result to do another left join on the 'project_enquiry_history' to find the items that have no entries.

You can also use these results as normal, to do selects of the data.

It will look something like:

SELECT * from project p LEFT OUTER JOIN project_history ph ON P.ID=ph.pid LEFT OUTER JOIN project_enquiry_history peh ON peh.ID=ph.pid WHERE (archived is NULL OR archived=0) AND (open is NULL OR open=1)

You may have to tweak this to find the most recent if you are using timestamps and such.

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