正如标题中所提到的,我正在努力寻找一个可以显示所有用户的SQL查询'昵称(来自用户表),有3个最常见的评级及其评级数,按照在评级表中的出现排序。
表格:
1. Users
+========+==========+
| userID | userName |
+--------+----------+
| 1 | User1 |
| 2 | User2 |
| 3 | User3 |
| 4 | User4 |
| 5 | User5 |
| 6 | User6 |
+========+==========+
2. Ratings (the rating column is irrelevant)
+========+========+
| userID | rating |
+--------+--------+
| 1 | 5 |
| 3 | 4 |
| 5 | 2 |
| 1 | 5 |
| 5 | 3 |
| 4 | 6 |
| 2 | 2 |
| 1 | 4 |
| 5 | 5 |
| 2 | 1 |
| 4 | 3 |
| 5 | 1 |
+========+========+
查询的结果将是:
User5 4
User1 3
User2 2
User4 2
这是我到目前为止的进展,虽然它显示没有值且未排序的用户,可能不是正确的方法:
SELECT userName
FROM Users
WHERE userID
IN(
SELECT userID s
FROM Ratings s
WHERE (
SELECT count( userID )
FROM Ratings
WHERE userID = s.userID
) >= (
SELECT COUNT( userID ) AS number
FROM Ratings
GROUP BY userID
ORDER BY number DESC
LIMIT 1
OFFSET 3
)
)
我感谢任何帮助,无论是完整的查询还是只是提示。提前谢谢!
答案 0 :(得分:1)
SELECT Z.* FROM
(
SELECT u.UserName,
COUNT( * ) AS NoOfOccurences
FROM Users u
JOIN
Ratings r
ON u.userID = r.userID
GROUP BY u.UserName
) Z
ORDER BY Z.NoOfOccurences DESC;
答案 1 :(得分:0)
我想我已经解决了,伙计们:
SELECT userName
FROM Users u
WHERE u.userID
IN (
SELECT userID
FROM Ratings r
WHERE (
SELECT COUNT( userID ) AS number
FROM Ratings
GROUP BY userID
ORDER BY number DESC
LIMIT 1
OFFSET 3
) <= (
SELECT count( userID )
FROM Ratings
WHERE userID = r.userID
)
)
ORDER BY (
SELECT count( userID )
FROM Ratings
WHERE userID = u.userID
) DESC