2009-09-08 185 views
0

我有三個表格設置:帖子,討論和評論。佈局如下:跨越多個表的分層子查詢可以引用父查詢嗎?

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 

一個帖子有許多討論,然後有許多評論。

我需要工作的是一個查詢,它會給我所有的帖子,但是每個帖子中的用戶數涉及。現在,通過「參與」,我的意思是我需要對所有發佈過帖子討論的用戶進行計數,或者對帖子的討論發表評論。很顯然,我的查詢需要確保它不包含同樣post_id的DISCUSSIONS表中的COMMENTS表中的重複項。

我能得到這個由子查詢指定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,以便每行返回每個帖子的適當計數。

這甚至可能嗎?需要做些什麼?

感謝, 賽斯

回答

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 
+0

UNION ...爲什麼我沒有想到這一點?謝謝。 – Seth 2009-09-09 00:41:22

+0

@我認爲我們可以避免工會,只是通過聯合來實現。我認爲這會很有效 – CrashOverload 2014-07-04 12:51:33