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.
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.