简体   繁体   English

SQL重复重复次数

[英]Sql Distinct Count of Duplicates

I am doing a query on a mysql database. 我正在对mysql数据库进行查询。 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. 希望您在每个UserFriendLink记录中都不会真正存储FirstName和LastName。 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). 如果是这样,是时候使用Users表(具有ID,First和Last)和UserFriendsLink表(具有UserID和FriendID)来规范化数据库了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM