简体   繁体   中英

SQL Left Join but don't want all records in the left table

I have 2 tables - Projects and Status Updates. The Project table has fields for id, priority, and status (among others) and my Status update table has fields for ProjectID, and date among others.

I am trying to build a query that will pull all of the High priority projects that are not completed or cancelled and tell me which of those do not have a status update associated with them in the last 14 days.

I have the following, but it is giving me all projects from the left table and not filtering on High priority projects who's status is not Completed or Cancelled.

ANY HELP WOULD BE GREATLY APPRECIATED.

Select proj.id, proj.Priority, proj.status, proj.ProjectName,  status_tmp.statusdate,     status_tmp.statusdetail

FROM proj 

LEFT JOIN (SELECT s1.*
FROM projectstatus AS s1
LEFT JOIN projectstatus AS s2
ON s1.statusproj = s2.statusproj AND s1.statusdate < s2.statusdate

WHERE s2.statusproj IS NULL ) as status_tmp

ON (proj.id=status_tmp.statusproj)

where proj.Priority='High' AND proj.status!='Cancelled' and 
proj.status!='Completed' AND 
status_tmp.statusdate < DATE_SUB(CURDATE(),INTERVAL 14 DAY) OR 
status_tmp.statusdate IS null 

Try putting a parenthesis in the last part of your where clause as so:

Select proj.id, proj.Priority, proj.status, proj.ProjectName,  status_tmp.statusdate,     status_tmp.statusdetail

FROM proj 

LEFT JOIN (SELECT s1.*
FROM projectstatus AS s1
LEFT JOIN projectstatus AS s2
ON s1.statusproj = s2.statusproj AND s1.statusdate < s2.statusdate

WHERE s2.statusproj IS NULL ) as status_tmp

ON (proj.id=status_tmp.statusproj)

where proj.Priority='High' AND proj.status!='Cancelled' and 
proj.status!='Completed' AND 

(status_tmp.statusdate < DATE_SUB(CURDATE(),INTERVAL 14 DAY) OR 
status_tmp.statusdate IS null )

If your status table has only the ProjectID as key:

SELECT P.*
FROM
    proj P
        LEFT JOIN projectstatus S ON P.id = S.ProjectID
WHERE
    P.Priority = 'High'
    AND P.status NOT IN ('Cancelled', 'Completed')
    AND
        (
        S.statusdate < DATE_SUB(CURDATE(), INTERVAL 14 DAY)
        OR
        S.statusdate IS NULL
        )

Otherwise you'll need filtering on the status table as well to select the currentmost status (this may not be true).

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