简体   繁体   English

SQL左联接:选择最后一条记录

[英]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. 我想获取所有发布的评论> 30天或没有评论的项目的列表。 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 项目:id,officialStatus
  • comments: id, projectID, postedOn 评论: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 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. 我认为您的主要问题是外部联接,这正是您所不需要的...在此调整中,没有注释的项目的max_posted日期为NULL。

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) http://sqlfiddle.com/#!2/ec919/17-以及执行计划(感谢@Barbara在sqlfiddle上准备此测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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