如何在嵌套连接的sql查询中添加列?

时间:2014-04-07 18:31:48

标签: sql ms-access

我正在使用Access并有三个表:CategoryTopicPost。我想要实现的是在结果中包含上次创建帖子的日期。

Post表格有一个CreatedOn列。

目前我的查询如下:

SELECT
    category.id,
    category.CategoryName,
    category.Description,
    count(tp.topic.id) AS NumberOfTopics,
    Sum(numofposts) AS NumberOfPosts
FROM category
LEFT JOIN (
    SELECT
        topic.id,
        topic.categoryId,
        count(post.id) AS numofposts
    FROM
        topic
        LEFT JOIN post ON topic.id = post.topicId 
    GROUP BY topic.id, topic.categoryId
) AS TP ON category.id=TP.categoryid
GROUP BY category.id, category.CategoryName, category.Description;

我最好的尝试(在我看来)是以下列方式扩展查询:

SELECT
    category.id,
    category.CategoryName,
    category.Description,
    COUNT(topic.id) AS NumberOfTopics,
    sum(numofposts) AS NumberOfPosts,
    "DUMMY" AS last
FROM category
LEFT JOIN (
    SELECT
        topic.id,
        COUNT(ps.id) AS numofposts,
        topic.categoryId 
    FROM topic
    LEFT JOIN (
        SELECT
            id,
            CreatedOn,
            topicId
        FROM post
        ORDER BY post.CreatedOn DESC
    ) AS ps ON topic.id = ps.topicId
    GROUP BY topic.id, topic.categoryId
)  AS TP ON category.id=TP.categoryid
GROUP BY category.id, category.CategoryName, category.Description;

不幸的是,我尝试了许多不同的方法来获得它,但我仍然没有成功。

提前致谢。

1 个答案:

答案 0 :(得分:0)

使用内联SELECT子句:

SELECT
    c.id,
    c.CategoryName,
    c.Description,
    (SELECT count(t.id)
     FROM topic t
     WHERE t.categoryId = c.id
    ) AS NumberOfTopics,
    (SELECT count(p.id)
     FROM post p
     JOIN topic t ON p.topicId = t.id
     WHERE t.categoryId = c.id
    ) AS NumberOfPosts,
    (SELECT max(p.createdOn) FROM post p
     JOIN topic t ON p.topicId = t.id
     WHERE t.categoryId = c.id
    ) AS LastPostDate
FROM category c;

这可能不是最有效的查询,但会产生正确的结果。

请参阅http://www.sqlfiddle.com/#!3/165d1/2了解演示。