I have the following tables in a PostgreSQL:
Categories | Locations | Checkins | Users | Friendships
id | id | id | id | user_id
name | category_id | location_id | gender | friend_id
icon | name | user_id | |
Now, i want to retrieve the following information about a venue
- How many female and male users a location has
- Category name and icon
- Location name
- How many friends have checked in at a location (from a given user id)
Except the last point, I solved it. But I have troubles to count the friends from a given user id. I tried it with this query:
SELECT distinct locations.id,
max(locations.name) as name,
max(locations.location) as location,
max(categories.name) as cat,
max(categories.icon) as caticon,
SUM(CASE WHEN users.gender = 'm' THEN 1 ELSE 0 END) AS male,
SUM(CASE WHEN users.gender = 'f' THEN 1 ELSE 0 END) AS female,
SUM(CASE WHEN friendships.user_id = 1 OR friendships.friend_id=1 THEN 1 ELSE 0 END) AS friends
FROM locations
INNER JOIN checkins ON checkins.location_id = locations.id
INNER JOIN users ON users.id = checkins.user_id
INNER JOIN categories ON categories.id = locations.category_id
LEFT JOIN friendships ON friendships.user_id = users.id OR friendships.friend_id = users.id
WHERE locations.id=7
GROUP BY locations.id
But I get a wrong number of the count for female users. Any idea what I’m doing wrong? I think I need a left join for the friendships table, because if a user has no friends (or no user is given) it should only return 0 for the friend count.
Hope I made myself clear,
thx, tux
1 Answer