跨多个表的分层子查询是否可以引用父查询?

时间:2009-09-08 17:48:35

标签: sql mysql performance join subquery

我有三个表设置:POSTS,DISCUSSIONS和COMMENTS。布局如下:

POSTS
id | user_id | title | body | created

DISCUSSIONS
id | post_id | user_id | title | body | created

COMMENTS
id | post_id | discussion_id | user_id | title | body | created

帖子有很多讨论,然后有很多评论。

我需要工作的是一个查询,它将为我提供所有的POSTS,但每个帖子中包含所涉及的用户数。现在,通过“参与”,我的意思是我需要计算所有用户,他们要么在帖子上发布讨论,要么对帖子的讨论之一发表评论。显然,我的查询需要确保它不计算COMMENTS表中同样位于同一post_id的DISCUSSIONS表中的重复项。

我可以通过在子查询中指定post_id来“手动”工作,如下所示:

SELECT posts.id AS posts_id, posts.user_id AS posts_user_id, posts.title AS posts_title, posts.created AS posts_created, users_profile.name AS users_profile_name,(anon_1.discussions_users_count + anon_1.comments_users_count) AS anon_1_users_count
FROM users_profile, posts LEFT OUTER JOIN (
    SELECT discussions.post_id AS post_id, count(*) AS discussions_users_count, (
        SELECT count(discussion_comments.user_id) FROM discussion_comments WHERE discussion_comments.user_id NOT IN (
            SELECT discussions.user_id FROM discussions WHERE discussions.post_id = 1 GROUP BY discussions.user_id
        )
        AND discussion_comments.post_id = 1 GROUP BY discussion_comments.user_id
    ) AS comments_users_count FROM discussions GROUP BY discussions.post_id
) AS anon_1 ON posts.id = anon_1.post_id WHERE posts.user_id = users_profile.user_id ORDER BY posts.created DESC  LIMIT 10 OFFSET 0

然而,这显然对我没有任何好处,因为我需要能够让子查询引用父查询的post.id,以便每行返回每个帖子的相应计数。

这甚至可能吗?需要什么?

谢谢, 塞特

1 个答案:

答案 0 :(得分:3)

我试试这个。

SELECT post_id, count(DISTINCT user_id)
FROM 
(
    SELECT id as post_id, user_id FROM posts
    UNION
    SELECT post_id, user_id FROM discussions
    UNION 
    SELECT post_id, user_id FROM comments
) a
GROUP BY post_id
相关问题