Forum Moderators: open
I would like to end up with a join that groups by userID and looks like the following:
userID ¦ count_posts_by_this_user ¦count_votes_cast_by_this_user ¦
1 -----¦-------------- 22-----------------¦--------------154--------------¦
2 -----¦-------------- etc----------------¦--------------etc--------------¦
userID is the primary key in (users)
userID a foreign key in both (posts) and (ratings)
postID and ratingID are both unique indentifiers.
The following query works fine to count posts (it is only a 2 table join):
SELECT *,
COUNT(posts.postID) as post_count
FROM posts, users
WHERE posts.userID = posts.userID
GROUP BY users.userID
But when I try to join 3 tables and add another COUNT (to count all of this user's submitted votes) using this query:
SELECT *,
COUNT(recipes.recipeID) as recipe_count, COUNT(ratings.ratingID) as ratings_count
FROM recipes, users, ratings
WHERE recipes.userID = users.userID AND
users.userID = ratings.userID
GROUP BY users.userID
all goes wrong. I get counts that are incredibly high (obviously due to some join problem).
What exactly am I missing? My guess is my join is somehow going awry.