3

我有一个我似乎无法应对的挑战。

+------+--------+-----------+-------+
|  id  |  user  |  genres   | books |
+------+--------+-----------+-------+
|  1   |  John  |  crimes   |   2   |
|  2   |  John  |  scienc   |   1   |
|  3   |  John  |  nature   |   4   |
|  4   |  Pete  |  nature   |   3   |
|  5   |  Pete  |  crime    |   2   |
|  6   |  Mary  | nature    |   20  |
+------+--------+-----------+-------+

我想要一个 SQL 查询来获取用户拥有的书籍总量,无论类型如何,并希望按拥有最多的人排序。

在此示例中,您看到 Mary 有 20 本书,Pete 5 和 John 有 7 本书,所以我想要的结果将是一个数组,如:

result[0][user] = "Mary";
result[0][total] = 20;
result[1][user] = "John";
result[1][total] = 7;
result[2][user] = "Pete";
result[2][total] = 5;

我怎样才能把它变成一个 SQL?我应该使用 CONCAT 还是 TOP 什么的?我使用 MySQL 和 PHP。

4

3 回答 3

6

你需要 GROUP BY 和 SUM

SELECT `user`, SUM(books) AS total_books
FROM `table`
GROUP BY `user`
ORDER BY total_books DESC

如果您只想要前 10 个,那么您可以使用

SELECT `user`, SUM(books) AS total_books
FROM `table`
GROUP BY `user`
ORDER BY total_books DESC LIMIT 10`

顺便说一句,您可能想稍微重新考虑一下您的架构。复制信息违反了规范化原则。您可能想要添加一个新owners表:

  +-----------+-------------+
  | owner_id  |  owner_name |
  +-----------+-------------+
  |     1     |    John     |
  |     2     |    Pete     |
  |     3     |    Mary     |
  +-----------+-------------+

然后owner_id在你的books表中引用它。

于 2012-04-06T12:07:27.180 回答
2
select user, sum(books) as total
from your_table
group by user
order by sum(books)
limit 10
于 2012-04-06T12:07:16.207 回答
1
SELECT sum(books) as book_count, user  FROM `books` GROUP BY (user) order by book_count DESC
于 2012-04-06T12:18:39.970 回答