我有以下两个表的架构:
Users(first_name,last_name,age,gender)
Friends(friend_one,friend_two)

其中first_nameUsers中的键,而'Friends'表(friend_onefriend_two)中的值实际上是从'Users'表中获取的first_name。 (表示参照完整性在Users(first_name)Friends(friend_one,friend_two)之间保持。

我正在尝试使用正确的MySQL查询来获取“十个最受欢迎的朋友”,这意味着拥有最多朋友的10个用户。
我的第一次尝试是:

SELECT first_name,COUNT(first_name)
FROM users,friends
WHERE first_name=friend_one OR first_name=friend_two
GROUP BY first_name;


因此,首先,我不确定这是否是正确的查询,更明显的问题是它不会产生前十名。
我知道SQL具有关键字TOP,但是我正在使用MySQL。
以上查询正确吗?如果不是,为什么,如何获得前十名?

最佳答案

这是我如何编写您的查询版本:

SELECT u.first_name, COUNT(first_name) as NumFriends
FROM users u join
     friends f
     on u.first_name = f.friend_one OR u.first_name = f.friend_two
GROUP BY u.first_name
ORDER BY NumFriends
LIMIT 10;


如果friends是对称关系,并且任何两个朋友之间只有一行,则此方法将起作用。如果朋友可以有多行(所以person1可以与person2成为朋友,反之亦然),则这可能会使数字过多。目前尚不清楚是否可行。

请注意,我“修复”了查询以使用正确的join语法,添加了表别名(表名的缩写)以及order bylimit子句。

07-24 09:37
查看更多