SQL left join:选择最后的记录

时间:2013-07-24 18:42:49

标签: sql sql-server-2000

我有一个项目表和一个评论表。一个项目可以有很多评论。我想获得评论发布的所有项目列表> 30天或项目没有评论。完成此任务的最佳方法是什么?

我有许多不成功的尝试;这是我的最新动态。

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

请在答案中使用这些表/列名称:

  • 项目:id,officialStatus
  • 评论:id,projectID,postedOn

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

我认为你的主要问题是外连接,这正是你不需要的......在这个调整中,没有注释的项目将有一个NULL max_posted日期。

答案 2 :(得分:0)

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 - 还有执行计划(感谢@Barbara在sqlfiddle上准备此测试)