I'm trying to do a select query that takes all the rows in one table, Locations, and then counts the number of people at those locations. That's defined in a UserLocations table. So that should be easy enough. But, I also want to find the number of friends at the location. Friendships are defined by a userid-friendid relationship in the Friendships table.
The FriendId in Friendships, in this query, matches up with the UserId in UserLocations
Locations
LocationName
LocationId
UserLocations
LocationId
UserId (refers to users table)
Friendships
FriendId
UserId
(both refer to users table)
So far, I've got something like this. It returns the Locations very well, but it messes up the counts. Where am I going wrong?
[CODE] $sql = "SELECT l.LocationName as LocationName, l.LocationId as LocationId,
COUNT(ul.UserId) as TotalAtLocation,
COUNT(f.FriendId) as FriendsAtLocation
FROM Locations l
LEFT JOIN UserLocations ul ON l.LocationId = ul.LocationId
LEFT JOIN Friendships f ON ul.UserId = f.FriendId
GROUP BY l.LocationId";[/CODE]
Any thoughts? I'm lost. And I guess I don't totally understand Joins, Counts, or Group Bys either.
Thanks guys.