使用表关系编写复杂的SQL查询

时间:2012-12-31 22:59:30

标签: sql many-to-many

我将首先展示我的表格结构(仅提及相关字段)

/* 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,但我认为计数和排序高于我目前的水平。请帮忙吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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