0

我有一张项目表和一张评论表。一个项目可以有很多评论。我想获得发表评论> 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
4

3 回答 3

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

于 2013-07-24T19:19:56.813 回答
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 日期。

于 2013-07-24T18:52:02.607 回答
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 上准备这个测试)

于 2013-07-24T19:31:27.773 回答