寻求有关SQL查询的帮助

时间:2013-04-02 14:16:05

标签: mysql sql database optimization

我正在寻找一种从我的sql表中检索数据的更好方法。

Table 1: User data
- User Id
- User Created date

Table 2: Mapping of the user with a role
- User Id
- Role

Table 3 
Role definition

Table 4 (may or may not have user data based on his activities on the site)
User data
Eg.
- User Id
- Total counts of the number of visits made on the portal

我希望编写最少量的查询(最好是1)来执行以下操作

* 我想打印总数最高的每种角色类型的最高用户*

输出将如下所示:

Header UserId---Rolename--Total Count
Row1   Test1 ---Staff   --1293
Row2   Test2 ---Faculty --1223
Row3   Test3 ---Dean    --2283928

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这就是你要找的东西:

SELECT a.UserId, b.Role, c.TotalCount
FROM TABLE1 as a join Table2 as b on a.UserId = b.UserId
                 join Table 4 as c on a.UserId = c.UserId
ORDER BY c.TotalCount DESC
LIMIT 3