There are s开发者_开发问答omething like communities with categories, groups and posts. I need to select all posts that are related to user. These relationships are that all posts that are made in any group where I am a member are needed. I accomplish it with query with sub-query.
Now, I want to somehow optimize it so I have only one query without sub-query. Only problem, I'm not sure how. At this point, I'm looking for a help.
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. */
If you need table structure, just ask. Huge thanks in advice!
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. */
should do the trick. At least, it should be equivalent to the query in the question - if it is consistent, I don't know.
Try this
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
精彩评论