0

I am doing a query on a mysql database. I have a main table where users are stored and another table where friends of that user are stored. For each user I want to see how many friends they have. This is what I'm getting.

ID    FirstName LastName FriendID
1     Andrew    Smith     1
1     Andrew    Smith     5
1     Andrew    Smith     9
2     John      Doe       3
2     John      Doe       5

This is what I want to get.

ID    FirstName LastName Friends
1     Andrew    Smith     3
2     John      Doe       2

If this is not enough detail to go on let me know and I will also show the tables and query I used.

2
  • 2
    Is it right that John Doe (ID 2) maps to the same FriendID (3) twice and count as 2 friends? Commented Nov 24, 2010 at 22:25
  • Oh you're right, updated. I was trying to do the count without using the group by clause Commented Nov 25, 2010 at 17:43

1 Answer 1

4
 SELECT ID, FirstName, LastName, COUNT(FriendID) AS Friends
    FROM Users GROUP BY ID, FirstName, LastName

One hopes you're not really storing FirstName and LastName in every UserFriendLink record. If you are, it's time to normalize your database with a Users table (with ID, First, and Last) and a UserFriendsLink table (with UserID and FriendID).

Sign up to request clarification or add additional context in comments.

3 Comments

In this example we can assume that users have lots of info associated with them. And that friends will never be users. My actual application is a bulletin board where there are posts and post replies. <br />for every post there can be multiple replies, replies have less fields associated with them and a reply will never be a post. but the example I gave above illustrates that relationship
The table I showed above was the result of my left join query which joined a few normalised tables
Thanks for the help, it was the group by that I was missing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.