0

我将首先介绍我的表结构(仅提及相关字段)

/* The table Users */

user_id | user_name | user_registration_date
1       | USER1     | 19/09/2010
2       | USER2     | 20/09/2010


/* The table Levels_Completed */

user_id | level_id
1       | 1
1       | 2
2       | 1

我想显示一个记分牌。列表中的第一个用户将是他完成的关卡数量最多的用户。对于上面的示例,USER1 将显示在 USER2 上方。

我想接收下一个数据:

user_id, user_name, user_registration_date, COUNT(level_id rows) AS score

对于我收到的每个 SQL 行,按分数计数排序。例子:

1 | USER1 | 19/09/2010 | 2
2 | USER2 | 20/09/2010 | 1

我知道如何使用INNER JOIN,但我认为计数和排序都在我目前的水平之上。请帮忙?

4

3 回答 3

2
SELECT Users.user_id, user_name, user_registration_date, COUNT(level_id) AS score
FROM Users INNER JOIN Levels_Completed ON Users.user_id = Levels_Completed.user_id
GROUP BY Users.user_id, user_name, user_registration_date
于 2012-12-31T23:02:08.913 回答
0

尝试这个:

SELECT
   U.user_id,
   U.user_name,
   U.user_registration_date,
   COUNT(L.level_id) as score
FROM Users U
   LEFT JOIN Levels_Completed L
       ON U.User_Id = L.User_Id
GROUP BY U.user_id, U.user_name, U.user_registration_date
ORDER BY score DESC
于 2012-12-31T23:07:44.673 回答
0
SELECT Users.user_id, user_name, user_registration_date, score
FROM Users
INNER JOIN (
  SELECT user_id, COUNT(level_id) AS score
  FROM Levels_Completed
  GROUP BY user_id)
USING (user_id)
ORDER BY score DESC
于 2012-12-31T23:09:34.297 回答