2011-08-12 150 views
0

有類似社區的類別,組和帖子。我需要選擇所有與用戶相關的帖子。這些關係是需要在我所屬的任何組中創建的所有帖子。我用子查詢查詢完成它。將此查詢與子查詢合併爲一個查詢

現在,我想以某種方式優化它,所以我只有一個查詢沒有子查詢。唯一的問題,我不知道如何。在這一點上,我正在尋求幫助。

SELECT ... /* Lot of stuff. */ 
FROM `posts` 

JOIN `groups` 
ON (`groups`.`id` = `posts`.`group_id`) 

JOIN `users` 
ON (`users`.`id` = `posts`.`user_id`) 

WHERE `groups`.`id` IN (SELECT `group_id` FROM `group_members` WHERE `user_id` = '33') /* My sub-query. ID '33' is variable.*/ 
AND `posts`.`post_id` = 0 /* For only first level posts. */ 

如果您需要表格結構,只需詢問。非常感謝您的建議!

回答

1
SELECT ... /* Lot of stuff. */ 
FROM `posts` 

JOIN `groups` 
ON (`groups`.`id` = `posts`.`group_id`) 

JOIN `users` 
ON (`users`.`id` = `posts`.`user_id`) 

JOIN `group_members` 
ON (`groups`.`id` = `group_members`.`group_id`) 

WHERE `group_members`.`user_id` = '33' 
AND `posts`.`post_id` = 0 /* For only first level posts. */ 

應該做的伎倆。 至少,它應該相當於問題中的查詢 - 如果它是一致的,我不知道。

0

試試這個

SELECT ... /* Lot of stuff. */ 
FROM `posts` 

JOIN `groups` 
ON (`groups`.`id` = `posts`.`group_id`) 

JOIN `users` 
ON (`users`.`id` = `posts`.`user_id`) 

inner join `group_members` on (`groups`.`id` = `group_members`.`group_id`) 
Where `group_members`.`user_id` = '33' AND `posts`.`post_id` = 0