简体   繁体   中英

SQL left join: selecting the last records

I have a table of projects and a table of comments. A project can have many comments. I want to get a list of all projects where the comment postedOn is > 30 days OR projects with no comment. What is the best way to accomplish this?

I've had many unsuccessful attempts; this is my latest go at it.

SELECT p.id, 
       p.officialStatus, 
       c.posted 
  FROM projects p 
       LEFT JOIN 
       (
        SELECT max(posted) as posted, 
                   projectid 
          FROM comments 
             WHERE DATEDIFF(day, posted, GETDATE()) > 30 
                   OR comment IS NULL
               group by projectid
        ) c ON p.id = c.projectid 
 WHERE (p.officialStatus NOT IN ('Blue', 'Canceled'))

Please use these table/column names in your answer:

  • projects: id, officialStatus
  • comments: id, projectID, postedOn
SELECT projects.id FROM projects
  LEFT JOIN
    (SELECT comments.projectID 
       FROM comments
      GROUP BY comments.projectID
      HAVING DATEDIFF(Now(), MAX(comments.postedOn)) < 30) AS C
  ON projects.id = C.projectID
  WHERE C.projectID IS NULL;

http://sqlfiddle.com/#!2/ec919/14

 SELECT PROJ.id,
        PROJ.officialStatus
   FROM Projects PROJ
        LEFT JOIN
        (
            SELECT projectid, MAX(posted) AS max_posted
              FROM Comments 
                   GROUP BY projectid
        )  COMMENTS ON PROJ.id = COMMENTS.projectid
  WHERE PROJ.officilstatus NOT IN ('Blue', 'Cancelled)
        AND COMMENTS.max_posted IS NULL
         OR COMMENTS.max_posted >= DATEADD(day, -30, Now())

I think your main problem was the outer join, which was exactly what you didn't need... In this tweak, projects with no comments will have a NULL max_posted date.

select p.*, max(c.postedOn) as postedDate from Projects p
left join Comments c on p.id = c.projectId
group by p.id
having COALESCE( postedDate, DATE_SUB(CURRENT_DATE, INTERVAL 31 DAY ) ) < 
    DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY );

http://sqlfiddle.com/#!2/ec919/17 - also with execution plan (thanks @Barbara for preparing this test on sqlfiddle)

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